Club.noww.in
Recently, a Python developer asked me how to save variables to files in Python. This is a very useful topic, and there are various methods to use it. In this tutorial, I will show you how to write variable to file in Python using different methods with examples.
To write a variable to a file in Python using the write() method, first open the file in write mode with open('filename.txt', 'w'). Then, use file_object.write('Your string here\n') to write the string to the file, and finally, close the file with file_object.close(). This method is ideal for writing simple string data to a file efficiently.
Python Write Variable to File
Let me first show you the basic syntax for writing to a file in Python. The most common methods to write variables to a file in Python are are write(), writelines(), and using the print() function with the file parameter.
Using write()
The write() method writes a string to a file in Python. This method does not add a newline character (\n) at the end of the string, so you need to include it explicitly if required.
file_object = open(r'C:\MyFolder\filename.txt', 'w') file_object.write('Your string here\n') file_object.close()I executed the above Python code using VS code, and you can see the exact output in the screenshot below:
Check out Save Python Dictionary to a CSV File
Using writelines()
The writelines() method writes a list of strings to a file in Python. Each string in the list is written as a separate line. Note that you need to include newline characters (\n) in the strings if you want each string to appear on a new line.
Let me show you an example.
file_object = open(r'C:\MyFolder\filename.txt', 'w') file_object.writelines(['First line\n', 'Second line\n', 'Third line\n']) file_object.close()You can see the exact output in the screenshot below:
Using print()
You can also use the print() function with the file parameter to write to a file in Python. This method automatically adds a newline character at the end of the string.
Here is an example.
with open(r'C:\MyFolder\filename.txt', 'w') as file_object: print('Your string here', file=file_object)Check out Download and Extract ZIP Files from a URL Using Python
Write Different Variable Types to a File in Python
Now, let me show you how to write different variable types to a file in Python.
Writing Strings
Writing a string variable to a file is straightforward. Let’s say we have a string variable containing a message.
message = "Hello, Python developers in the USA!" with open(r'C:\MyFolder\message.txt', 'w') as file_object: file_object.write(message + '\n')Here is the exact output you can see in the screenshot below:
Writing Integers and Floats
To write integers or floats, you need to convert them to strings first. This can be done using the str() function or formatted strings.
age = 30 height = 5.9 with open(r'C:\MyFolder\personal_info.txt', 'w') as file_object: file_object.write(f"Age: {str(age)}\n") file_object.write(f"Height: {str(height)}\n")Check out Read Binary File in Python
Writing Lists
You can write lists to a file by converting each element to a string and joining them with newline characters. This method is useful for writing each item of the list on a new line.
names = ["John Doe", "Jane Smith", "Emily Davis"] with open(r'C:\MyFolder\names.txt', 'w') as file_object: file_object.writelines([name + '\n' for name in names])Writing Dictionaries
For dictionaries, you can write each key-value pair on a new line. This method is useful for saving configuration settings or user information.
user_info = {"name": "Alice Johnson", "age": 28, "city": "New York"} with open(r'C:\MyFolder\user_info.txt', 'w') as file_object: for key, value in user_info.items(): file_object.write(f"{key}: {value}\n")You can see the exact output in the screenshot below:
Read Python Create File
Advanced Methods to Save Variables to File in Python
Now, let me show you other methods to save a variable to a file in Python.
Using json Module
For complex data structures, like nested dictionaries or lists, consider using the json module. This module allows you to serialize Python objects to JSON format, which is a widely used data interchange format.
import json data = { "name": "Michael Scott", "age": 45, "city": "Scranton", "profession": "Regional Manager" } with open(r'C:\MyFolder\data.json', 'w') as file_object: json.dump(data, file_object)Using CSV Module
For tabular data, the csv module is very useful. This module allows you to write data in CSV (Comma-Separated Values) format, which is commonly used for spreadsheets and databases.
import csv data = [ ["Name", "Age", "City"], ["Jim Halpert", 34, "Scranton"], ["Pam Beesly", 33, "Scranton"] ] with open(r'C:\MyFolder\employees.csv', 'w', newline='') as file_object: writer = csv.writer(file_object) writer.writerows(data)Read Python Get File Extension
Using pickle Module
If you need to serialize and store Python objects, the pickle module is a great choice. This module allows you to serialize and deserialize Python objects, making saving and loading complex data structures easy.
import pickle data = { "name": "Dwight Schrute", "age": 40, "city": "Scranton", "profession": "Assistant to the Regional Manager" } with open('data.pkl', 'wb') as file_object: pickle.dump(data, file_object)Handle File Exceptions
When working with files, it’s essential to handle exceptions to avoid potential errors. The try-except block is useful for this purpose.
try: with open('data.txt', 'w') as file_object: file_object.write("Some important data\n") except IOError as e: print(f"An error occurred: {e}")Conclusion
In this tutorial, I explained how to write variables to a file in Python using different methods, such as using write(), writelines(), print(), etc. I have also provided some examples of adding different variable types to a file in Python.
You may also like: