Python write to file example

How to Write to a Text File in Python

In Python, you can write to a text file by following these three steps:

You can skip the last step by using the with statement.

with open("example.txt", "w") as f: f.write("Hello world!")

This piece of code creates a new file called example.txt and writes “Hello World” into it.

In this guide, you are going to learn the basics of writing to a file in Python.

Python How to Write to a File in Detail

To write to a file in Python, use these three steps:

  1. Open a text file with the open() function.
  2. Write text to the opened file with the write() method.
  3. Finally, close the file using the close() method. Another options is to use the with statement that automatically closes the file for you. In this guide, I’m going to use the with statement.

The syntax for the open() function is as follows:

  1. path_to_a_file is the path to the file you want to open. If no file is found, a new one is created.
  2. mode specifies in which state you want to open the file. Use the mode ‘w’ to write to the file and ‘a’ to append to a file (add text to the end of the file).

The open() function returns a file object. This file object has two useful methods for writing text to the file:

  1. write() that writes a single string to the text file.
  2. writelines() that writes a list of strings to the file (or any other iterable, such as a tuple or set of strings).

Let’s see how to use these file-writing methods.

The write() Method in Python

The write() method takes a string argument. It writes this argument into the opened file.

For example, let’s create a list of strings and use the write() method to write each of the strings into the file using a for loop:

words = ["This ", "is ", "a ", "test"] with open("example.txt", "w") as f: for word in words: f.write(word)

As a result, a file called example.txt is created with the following content:

Notice how each string is written to the same line by default.

If you want to have each word appear on a separate line, write the line break character ‘\n’ after writing a string to the file.

words = ["This", "is", "a", "test"] with open("example.txt", "w") as f: for word in words: f.write(word) f.write("\n")

In the example.txt file the result looks like this:

This is one way to write into a file.

But in the case of multiple strings, you can use the writelines() method to write them all into a file on the same go.

Читайте также:  React select ref typescript

The writelines() Method in Python

The writelines() function takes an iterable object, such as a list, that contains strings to be written into the opened file.

For example, let’s repeat the above example using the writelines() method:

words = ["This ", "is ", "a ", "test"] with open("example.txt", "w") as f: f.writelines(words)

After running this piece of code, the example.txt file looks like this:

Now you know how to write text to a file in Python.

Next, let’s take a look at how to add text at the end of an already-existing text file.

How to Append to a File in Python

To add text at the end of a file after the existing lines of text, use the write mode ‘a’.

This mode is called the appending mode. Appending means adding to the end of something.

# Let's first write to a file with open("example2.txt", "w") as f: f.write("This is ") # Then let's reopen the file and append some text to it: with open("example2.txt", "a") as f: f.write("just another test.")

Here the result is a file called example2.txt with the following contents:

This is just another test.

As you can see, the last bits of text were successfully added to the end of the text file.

Conclusion

Today you learned how to write a file in Python.

To recap, to write a file, follow these three steps:

  1. Open the file with the open() function.
  2. Write to the file using either write() or writelines() method.
  3. Always close the file after writing. You can do this with the close() method or by using the with statement that automatically closes the file after writing.

See Also

Источник

Python Write to File

It is pretty standard that large chunks of data need to store in the Files. Python is widely used in data analytics and comes with some inbuilt functions to write data into files.

We can open a file and do different operations on it, such as write new contents into it or modify a file for appending content at the end of a file.

After reading this tutorial, you’ll learn: –

  • Writing into both text and binary files
  • The different modes for writing a file
  • Writing single or multiple lines in a file.
  • All methods for writing a file such as write() and writeline() .
  • Appending new contents at the end of an existing file
  • Open file for both reading and writing.

Table of contents

Access Modes for Writing a file

Access mode specifying the purpose of opening a file.

Whenever we need to write text into a file, we have to open the file in one of the specified access modes. We can open the file basically to read, write or append and sometimes to do multiple operations on a single file.

To write the contents into a file, we have to open the file in write mode. Open a file using the built-in function called open() . This function takes two parameters, namely filename, and access mode, and returns the file pointer.

We can open a file for modifying or overwrite its contents by using any one of the modes described in the following table.

File after writing a text in it

Note: A new file is created in the directory where this Python script is present. Use the absolute path If you want to create and write a file in some other directory.

Читайте также:  Main css как подключить

An absolute path contains the entire path to the file or directory that we need to access. It includes the complete directory list required to locate the file.

For example, E:\PYnative\files_demos\write_demo.txt is an absolute path to discover the write_demo.txt

fp = open(r"E:\demos\files\write_demo.txt", 'w') fp.write('This is new content') fp.close() 

Writing To An Existing File

In an already existing file, while opening the file in the write mode, the existing content will be overwritten. The filehandle will be placed at the beginning of the file.

In the below example, we are reading a file to view the old contents. Next, we are opening a file in the write mode to write the new content. We can see that the existing content has been overwritten with the new content.

file_path = r"E:\demos\files\write_demo.txt" fp = open(file_path, 'r') print(fp.read()) fp.close() # overwriting existing content of a file fp = open(file_path, 'w') fp.write("This is overwritten content") fp.close() # Read file fp = open(file_path, 'r') print("Opening file again..") print(fp.read()) fp.close()
This is new content Opening file again.. This is overwritten content

File Write Methods

Python provides two different methods to write into a file. We don’t have to import any module for that.. Below are the methods.

File after writing list into it

with Statement to Write a File

We can open a file by using the with statement along with open() function. The general syntax is as follows.

with open(__file__, accessmode) as f:

The following are the main advantages of opening a file using ‘with’ statement

  • The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
  • This also ensures that a file is automatically closed after leaving the block.
  • As the file is closed automatically it ensures that all the resources that are tied up with the file are released.

Let us see with an example how we can use this to open a file for writing.

name = "Written using a context manager" with open("Write_demo.txt", "w") as f: f.write(name) # opening the file in read mode to access the file with open("Write_demo.txt", "r") as f: print(f.read())
Written using a context manager

Appending New Content to an Existing File

With the access mode set to a , the open function will place filehandle at the end of the file, and then we can add new text at the end of the existing file using the write() and writelines() functions.

Now let us add some content to the already created ‘Write_demo.txt’ .

name = '\nEmma' address = ['\nAddress: 221 Baker Street', '\nCity: London', '\nCountry:United Kingdom'] # append to file with open("Write_demo.txt", "a") as f: f.write(name) f.writelines(address) # opening the file in read mode to access the file with open("Write_demo.txt", "r") as f: print(f.read()) 
Written using a context manager Emma Address: 221 Baker Street City: London Country:United Kingdom

File after appending text

Append and Read on the Same File

In the above example, we have seen how our content got appended to the existing content in the end. We opened the file again to read the contents.

As you can see, we opened a file two times, one for appending and the second call for a reading.

If we try to read without opening the file again we will get the Unsupported operation exception .

name2 = "Antony\n" address2 = ["224 Baker Street\n", "London\n"] with open("Write_demo.txt", "a") as f: f.write(name2) f.writelines(address2) print(f.read())
UnsupportedOperation: not readable

It is possible to do both append and read operations together by using the access mode a+ . where we can open a file and add the content and then read the modified file again. We can perform multiple operations on the same file by using the + sign and the access mode that we wish to perform.

Читайте также:  Урок 14 объекты практикум javascript

Example: Append and Read

As mentioned above, the write() method moves the filehandle in the append mode at the end. If we try to read the file using the read() method, you’ll get an empty string. Use the seek() method on the file object and move the FileHandle to the beginning.

name = '\nAntony' address = ['\nAddress: 221 Baker Street', '\nCity: London', '\nCountry:United Kingdom'] # append to file with open("Write_demo.txt", "a+") as f: f.write(name) f.writelines(address) # move file handle to the start f.seek(0) print(f.read())
Written using a context manager Emma Address: 221 Baker Street City: London Country:United Kingdom Antony Address: 221 Baker Street City: London Country:United Kingdom

If you want to perform both write and read then change the access mode to w+. It opens a file for both writings as well as reading. The file pointer will be placed at the beginning of the file. For an existing file, the content will be overwritten.

# Write and Read with open("Write_demo.txt", "w+") as f: f.write('Kelly') # move file handle to the start f.seek(0) print(f.read())

Writing to a Binary File

The open() function, by default, opens a file in text mode. We can read the text file contents using the access mode as r and write new content in the text file using the access mode as w .

To read or write content to a binary file, use the access mode ‘B’. For writing, it will be wb , and for reading, it will be rb .

The open() function will check if the file already exists and if not, will create one. In the existing file, all the content will be deleted, and new content will be added.

file = open("Writedemo.bin", "wb") file.write("This is a sample string stored in binary format") file.close()

The above code will create a binary file and the write the string passed in the write() method.

Summary

In this article we have covered the basic methods for modifying a file. We also saw in detail the different access modes for performing the write operations. In addition to this we saw the different access modes for appending new content at the end of the file.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Оцените статью