Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions Python_Open-Read-&-Count-Text-File.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,33 @@
##Given a file path:
##read file, count total words and lines

##open, read, close file
a = open("hello.txt")
##Pulls/Imports
##open, read, close file
a = open("hello.txt") ##puth path to your text file
content = a.read()
a.close()

##count words in file and format output with placeholder and word list count
words = content.split()
print("There are {0} words in the file.".format(len(words)))
##Definitions:
##count words in file and format output with placeholder and word list count
def wordcount(a):
words = content.split()
print("There are {0} words in the file.".format(len(words)))

##count lines in file and format output with placeholder and line list count
num_lines = sum(1 for line in open("hello.txt"))
print("There are {0} lines in the file.".format(num_lines))
##count lines in file and format output with placeholder and line list count
def linecount(a):
num_lines = sum(1 for line in open("hello.txt"))
print("There are {0} lines in the file.".format(num_lines))

##count characters in file
def count_characters(content):
words = content.split()
counter = 0
for i in words:
counter = counter + len(i)
print("There are {0} characters in the file.".format(counter))


##Calls
wordcount(a)
linecount(a)
count_characters(content)