4th Nov 2021 9 minutes read How to Write to File in Python Xavier Rigoulet python python basics With Python, you can modify and write directly to a file programmatically, saving you the hassle of doing it manually. In this article, you will learn how to write to a file in Python. Before diving into the nitty-gritty of how to write to file in Python, I want to mention that I use Python 3.8.5 and Windows 10. However, your results should be the same on any operating system. It’s good to have some knowledge of file manipulation before you read this article. For more information, read How to Work with Files and Directories in Python and How to Rename Files with Python. If you're looking for help with Python assignments, understanding how to write to a file is a fundamental skill that will make your projects more efficient. And if you're working on a larger writing project, you can always reach out for assistance to write my research paper services. There are multiple ways to write to files and to write data in Python. Let’s start with the write() method. Use write() to Write to File in Python The first step to write a file in Python is to open it, which means you can access it through a script. There are two ways to open a file. The first one is to use open(), as shown below: # open the file in the write mode f = open('file.txt', 'w') However, with this method, you need to close the file yourself by calling the close() method: # close the file f.close() It is shorter to use the with statement, as we do not need to call the close() method. This is the method we’ll use in this tutorial: with open("file.txt", "w") as file: The above line of code will open file.txt and will assign the file handler to the variable called file. We can then call the write() method to modify our file programmatically. Let’s run an example: file.write("Python is awesome!") Once this command has been executed, we want to read the file to see if it has been updated. We need to call the read() method, as shown below: # Open and read the file after writing: with open("file.txt", "r") as file: print(file.read()) It’s important to note that the parameters in the open() function will decide where the write() method will be active. If you want to learn more on how to write files in Python with the write() method, check out our course on Working with Files and Directories in Python. Use writelines() to Add List Data to a File Another method that you can use is writelines(). This method adds terms of a list in a programmatic way. Let’s run an example: # open file with open("file2.txt", "a") as file: # write to file file.writelines(["Hey there!", "LearnPython.com is awesome!"]) #open and read the file after the appending: with open("file2.txt", "r") as file: print(file.read()) After checking the output, you will notice that writelines() does not add any line separators by default; we have to specify the line separator. We can modify our code with the following: # open and write to file with open("file2.txt", "a") as file: file.writelines(["Hey there!\n", "LearnPython.com is awesome!\n"]) # open and read the file after the appending: with open("file2.txt", "r") as file: print(file.read()) A more Pythonic and efficient way of doing it is: # open file with open("file2.txt", "a") as file: # set a list of lines to add: lines = ["Hey there!", "LearnPython.com is awesome!"] # write to file and add a separator file.writelines(s + '\n' for s in lines) #open and read the file after the appending: with open("file2.txt", "r") as file: print(file.read()) The code above will use new lines as the line separator. Writing Data to CSV Files in Python You might find it useful to be able to update a CSV file directly with Python. CSV stands for comma-separated values. If you are a data professional, you’ve certainly come across this kind of file. A CSV file is a plain text file containing a list of data. This type of file is often used to exchange data between applications. If you want to refresh your knowledge of CSV files, read our article How to Read CSV Files in Python. In this part, we will use Python’s built-in csv module to update a CSV file. When you want to write data to a file in Python, you’ll probably want to add one or more rows at once. The data can be stored in lists or a dictionary. Let’s explore some ways to write data to files in Python. Writing List Data to a CSV Let’s explore how to add a single row of data with writerow() and multiple rows of data with writerows(). Use writerow() for a Single Row To write in a CSV file, we need to open the file, create a writer object and update the file. Let’s run an example: # import import csv # Create header and data variables header = ['last_name', 'first_name', 'zip_code', 'spending'] data = ['Doe', 'John', 546000, 76] with open('customers.csv', 'w', encoding='UTF8', newline='') as file: # Create a writer object writer = csv.writer(file) # Write the header writer.writerow(header) # Write the data writer.writerow(data) For detailed information, it’s always a good idea to read the documentation. Now, let’s explore how to write data in Python when you need to add multiple rows of data. Use writerows() for Multiple Rows We can write multiple rows to a file using the writerows() method: # import import csv # Create header and data variables header = ['last_name', 'first_name', 'zip_code', 'spending'] data = [ ['Smith', 'Nicholas', 453560, 82], ['Thompson', 'Julia', 326908, 143], ['French', 'Michael', 678321, 189], ['Wright', 'Eva', 285674, 225], ['White', 'David', 213456, 167] ] with open('customers.csv', 'w', encoding='UTF8', newline='') as file: # Create a writer object writer = csv.writer(file) # Write the header writer.writerow(header) # Add multiple rows of data writer.writerows(data) We just added several rows to our file. You can find more information about the writerows() method in the documentation. Writing Dictionary Data to a CSV If each row of the CSV file is a dictionary, you can update that file using the csv module’s dictWriter() function. For example: # import import csv # csv header fieldnames = ['last_name', 'first_name', 'zip_code', 'spending'] # csv data rows = [{ 'last_name': 'bloggs', 'first_name': 'Joe', 'zip_code': 986542, 'spending': 367 },{ 'last_name': 'Soap', 'first_name': 'Bob', 'zip_code': 567890, 'spending': 287 },{ 'last_name': 'farnsbarns', 'first_name': 'Charlie', 'zip_code': 123456, 'spending': 245 }] with open('customers.csv', 'w', encoding='UTF8', newline='') as f: # Create a writer object writer = csv.DictWriter(f, fieldnames=fieldnames) # Write header writer.writeheader() # Write data from dictionary writer.writerows(rows) And that’s all you have to do! If you want to learn more on the topic, do not forget to check the course on working with files and directories in Python. Using pathlib to Write Files in Python Now let’s explore using the pathlib module to write to a file in Python. If you are not familiar with pathlib, see my previous article on file renaming with Python. It is important to note that pathlib has greater portability between operating systems and is therefore preferred. Use write_text() We can use the Path().write_text() method from pathlib to write text to a file. First, we use the Path class from pathlib to access file.txt, and second, we call the write_text() method to append text to the file. Let’s run an example: # import from pathlib import Path # Open a file and add text to file Path('file.txt').write_text('Welcome to LearnPython.com') Next, we'll use the is_file(), with_name() and with_suffix() functions to filter the files we want to update. We will only update those files that fulfill certain conditions. The is_file() function will return a Boolean value that’s True if the path points to a regular file and False if it does not. The with_name() function will return a new path with the changed filename. Finally, with_suffix() will create a new path with a new file extension. You can read about the details of these methods in the Python documentation. Let’s run an example that demonstrates all this. We will open our text file, write some text, rename the file, and save it as a CSV file. # import from pathlib import Path # set the directory path = Path.cwd() / 'file.txt' # Check if the file is a file if path.is_file(): # add text path.write_text('Welcome to LearnPython.com') # rename file with new extension path.replace(path.with_name('new_file').with_suffix('.csv')) File Manipulation in Python In this final part, we will explore file manipulation in Python using the tell() and seek() methods. Use tell() to Get the Current Position The tell() method can be used to get the current position of the file handle in the file. It helps to determine from where data will be read or written in the file in terms of bytes from the beginning of the file. You can think of the file handle as a cursor that defines where the data is read or written in the file. This method takes no parameter and returns an integer. Let’s run an example: # Open a file in read mode with open("file.txt", "r") as file: # print position of handle print(file.tell()) # prints 0 You can find more information in the Python documentation. Use seek() to Change Stream Positions The seek() method is used to change the stream position. A stream is a sequence of data elements made available over time, and the stream position refers to the position of the pointer in the file. The seek() method is useful if you need to read or write from a specific portion of the file. The syntax is: fp.seek(offset, whence) What does this mean? fp is the file pointer. offset is the number of positions you want to move. It can be a positive (going forwards) or negative (going backwards) number. whence defines your point of reference. It can be: 0: The beginning of the file. 1: The current position in the file. 2: The end of the file. If you omit the whence parameter, the default value is 0. When we open the file, the position is the beginning of the file. As we work with it, the position advances. The seek() function is useful when we need to walk along an open file. Let’s run a quick example: # Open a file with open("file.txt", "r") as file: file.seek(4) print(file.readline()) You can find more information in the Python documentation. Learn More About Working with Files in Python We covered a lot of ground in this article. You’re getting some solid knowledge about file manipulation with Python. Now you know how to write to a file in Python and how to write data to a file in Python. We also briefly explored the tell() and seek() methods to manipulate a file. Don’t forget to check our course on Working with Files and Directories in Python to deepen and solidify your Python knowledge! Tags: python python basics