Writing to a File
To write data to a file in Python, you can use the write() or writelines() methods of the file object.
To write some data, first open the file in write mode using the open() function. Specify the file name (eg data.txt), and the mode as `”w”`. This will create a new file or overwrite an existing file.
my_file = open(“data.txt”, “w”)
With the file open, there are multiple options you can use to write data to a file. You can use the write() method, or the writelines() method. The write() method is used to write a single string or a sequence of characters and allows for more flexibility in writing custom content.
my_file.write(“This is a sample text.”)
The writelines() method is convenient when you have a list that you want to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access