Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write text to file line by line [duplicate]

Tags:

python

file

I'm trying to write some text to a file, and here's what i tried :

text = "Lorem Ipsum is simply dummy text of the printing and typesetting " \
                  "industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s," \
                  " when an unknown printer took a galley of type and scrambled it to make a type specimen book."
target = open("file", 'wb')
target.writelines(text)

And I get an empty file. How can I do this?

like image 443
Ashref Avatar asked Nov 07 '16 20:11

Ashref


People also ask

How do you duplicate a line in Python?

Alternatively, you can press Ctrl+Shift+A , start typing the command name in the popup, and then choose it there. The duplicated line or multi-line selection is inserted below the original line or selection; the duplicated inline selection is inserted to the right of the original.


1 Answers

The code you've provided produces a file named file with the desired lines. Perhaps you meant to save it as "file.txt". Also, the 'b' in the 'wb' flag tells the code to write the file in binary mode (more information here). Try just using 'w' if you want the file to be readable.

Finally it is best practice to use the with statement when accessing files

text ="Lorem Ipsum is simply dummy text of the printing and typesetting " \
              "industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s," \
              " when an unknown printer took a galley of type and scrambled it to make a type specimen book."
with open("file.txt", 'w') as f:
    f.write(text)
like image 149
Mark Hannel Avatar answered Oct 09 '22 20:10

Mark Hannel