Reputation: 3
, i am having an issue when i tried to write a program in my Python. This is my requirement: 1) Accept the input ( its a csv file ) as a command line argument 2) Read this csv file 3) count the num of words and characters from this csv file 4) and write the results - num of words and characters of the csv file into an another text file - say results.txt
this is what i tried"
import sys
print('the version of python')
print(sys.version)
with open(sys.argv[1], 'rt') as f, open(sys.argv[2],'r') as fw:
contents = f.read()
words= contents.split()
print(' displaying words in txt file..', words)
print(' number of words in txt file..', len(words))
contents1 = fw.read()
words1= contents1.split()
print(' displaying words in txt file..', words1)
print(' number of words in txt file..', len(words1))
am not getting the results. the first sections, reading of the file from the csv is working fine now. but, how can i write into the results.txt file?
Upvotes: 0
Views: 1728
Reputation: 73
To write to a file you need to open it in "w" mode and then use .write()
function to write the contents. Something like this:
file1 = open("myfile.txt","w")
file1.write("Number of words: {}".format(len(words))
file1.close()
I hope it helps!
Upvotes: 1