Python Assignment – Reading and Writing Files Use comments to decribe your code
ID: 3867150 • Letter: P
Question
Python Assignment – Reading and Writing Files
Use comments to decribe your code
Open a file.
Type the following code:
fhand = open(‘aFile.txt’)
print fhand
What do you see?
To see the contents of the file type:
for line in fhand:
print line
Counting tokens (in our case, words) in a file
words = 0
fhand = open('aFile2.txt')
for line in fhand:
print line # Use for development – then remove
ln = line.split() # Transform a line of a file into a list
words += len(ln) # Returns the length of a list
print words # Use for development – then remove
print ‘Word count = ‘, words # Print outside of the loop
Explanation / Answer
#!usr/bin/python
fhand = open('file2.txt')
print (fhand) #it prints
for line in fhand: #printing the contents of file
print(line)
#Counting words in a file
words = 0
fhand = open('file3.txt')
for line in fhand:
print(line)
ln = line.split() # It splits the line into words separated by space.It gives a list of these words
words += len(ln) # adding the number of words in a line to the words (i.e total word count)
print (words) # printing the current word count
print('Word count = ', words) #print total word count
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.