You are currently viewing Reading from and writing to files in Python

Reading from and writing to files in Python

In Python, reading from and writing to files is a common operation. This involves opening a file, performing the desired operation (reading or writing), and then closing the file. Here are some examples of how to read from and write to files in Python:

Reading from a file

To read from a file in Python, we use the open() function to open the file and then use the read() method to read the contents of the file. Here’s an example:

# open the file for reading
file = open('example.txt', 'r')

# read the contents of the file
contents = file.read()

# close the file
file.close()

# print the contents of the file
print(contents)

In this example, we open a file called example.txt for reading using the open() function with the mode 'r'. We then read the contents of the file using the read() method and store them in a variable called contents. Finally, we close the file using the close() method and print the contents of the file using the print() function.

Writing to a file

To write to a file in Python, we use the open() function to open the file and then use the write() method to write the desired content to the file. Here’s an example:

# open the file for writing
file = open('example.txt', 'w')

# write to the file
file.write('This is some sample text.')

# close the file
file.close()

In this example, we open a file called example.txt for writing using the open() function with the mode 'w'. We then write the text 'This is some sample text.' to the file using the write() method. Finally, we close the file using the close() method.

Appending to a file

To append to a file in Python (i.e., add content to the end of an existing file), we use the open() function with the mode 'a' instead of 'w'. Here’s an example:

# open the file for appending
file = open('example.txt', 'a')

# append to the file
file.write('\nThis is some additional text.')

# close the file
file.close()

In this example, we open the file example.txt for appending using the open() function with the mode 'a'. We then append the text 'This is some additional text.' to the end of the file using the write() method, and close the file using the close() method.

It’s important to note that whenever you are working with files, you should always make sure to close them when you are finished using them. This helps to ensure that the file is properly saved and that any resources used to work with the file are freed up for other processes.

Leave a Reply