Writing Data to a File in Python has many methods.
1. The write() Method in Python
- The write() Method: writes any string to an open file.
The write() method does not add a newline character (‘\n’) to the end of the string:
Syntax:
fileObject . write(string);
content to be written into the opened file.
Example:
# Open a file
fo = open(“myfile.txt”, “w”)
fo.write( “Python is a great language.\nYeah its great!!”);
# Close opend file
fo.close()
The above method would create myfile.txt file and would write given content in that file and finally it would close that file. If you open this file, it would have following content
Python is a great language.
Yeah its great!!
2. Python writelines() method
With the writeline function you can write a list of strings to a file
>>> fh = open(“hello.txt”, “w”)
l>>> ines_of_text = [“Alcohol and Energy Drinks”, ” are”, ” dangerous”]
>>> fh.writelines(lines_of_text)
hello.txt
Alcohol and Energy Drinks are dangerous