Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a new text file in python

I'm writing code that goes over a text file counting how many words are in every line and having trouble putting the result (many lines that each consist ofa number) into a new text file.

My code:

in_file = open("our_input.txt")
out_file = open("output.txt", "w")


for line in in_file:
    line = (str(line)).split()
    x = (len(line))
    x = str(x)
    out_file.write(x)

in_file.close()  
out_file.close()

But the file I'm getting has all the number together in one line.

How do I seperate them in the file I'm making?

like image 313
dardi Avatar asked Jun 17 '26 23:06

dardi


1 Answers

You need to add a new line after each line :

out_file.write(x + '\n')

Also as a more pythonic way for dealing with files you can use with statement to open the files which will close the files at the end of the block.

And instead of multiple assignment and converting the length to string you can use str.format() method to do all of this jobs in one line:

with open("our_input.txt") as in_file,open("output.txt", "w") as out_file:
    for line in in_file:
        out_file.write('{}\n'.format(len(line.split())))
like image 135
Mazdak Avatar answered Jun 19 '26 11:06

Mazdak