Firstly, you have to open a file. You can do so with the built-in open() function. This function can take a few optional arguments, but the one argument you have to provide is the filename or path to the file. You should also consider the mode that you would like to open the file in. The default is read mode "r". In this mode you can pull information from the file, but you cannot write to it. Other useful modes include write mode "w", append mode "a", read-and-write mode "r+", read-and-write mode with truncation (see the next sentence) "w+", and binary read mode "rb". Note that both "w" and "w+" modes will blank out (AKA "truncate to 0") your file if it already exists so be careful using them. You can see all of the options in the documentation . So let's say you wanted to open a text file in write mode. You would do so with the line file_obj = open("/path/to/file", mode="w") From here you have a few options to write to the file. The easiest is the write() method. Here's an example use. file_obj.write("I taste a liquor never brewed\n") file_obj.write("From Tankards scooped in Pearl\n") file_obj.write("Not all the Frankfort Berries\n") file_obj.write("Yield such an Alcohol!") Notice that I have to end each line with a newline character \n because unlike say the print() function, write() does not automatically append a newline. Note however, that Python will often wait until it is "sure" that you are done writing to the file before actually pushing the text into the file. Until then it is stored in a buffer. The easiest way to ensure this happens is to close the file as soon as you are done with it. file_obj.close() Note that it is also useful to close a file opened in read mode if your program is going to be running for a while (for example, if it's running on a server) so that you also let Python's garbage collector clean up some memory required to keep the file open. Hence, when you open a file, you will almost always want to close it afterward. Since it is a very common error to forget to add that close() call, Python has our backs with an alternate way to both open and close a file. It's called a context manager and the syntax looks like this. with open("/path/to/file", mode="w") as file_obj: file_obj.write("I taste a liquor never brewed\n") file_obj.write("From Tankards scooped in Pearl\n") file_obj.write("Not all the Frankfort Berries\n") file_obj.write("Yield such an Alcohol!") # let's check if the file is still open print(file_obj.closed) # now let's check outside of the context manager print(file_obj.closed) Note that this is especially useful because that call to close the file will even get run if a runtime exception occurs. Reading a file has its own methods. Let's assume we've run the above code and created a file (make sure that you fill in "/path/to/file" with a filename that didn't previously exist before you run that code). Then we can read the whole thing into a string using the read() method. with open("/path/to/file") as file_obj: contents = file_obj.read() print(contents) We can instead read the file into a list of strings -- one for each line -- with the readlines() method or get just the next (starting with the first) line with readline(). I encourage you to test both of those methods out. However, one other very useful method of reading files in one line at a time is to use a for loop. with open("/path/to/file") as file_obj: for line in file_obj: print(line, end="") Exercise for the reader: see if you can reason out why I left out the mode argument to open() and why I specified end="" in the print() function based on what I've said so far. One final note: if you plan to do anything else to the file -- for example, renaming it, moving it, verifying it exists before opening it, etc -- then you can use the Path.open () method instead of the regular ol' open() function. Here's an example. from pathlib import Path file = Path("path/to/file") with file.open() as file_obj: for line in file_obj: print(line, end="") # and now that I've closed the file I can rename it or whatever References: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open https://docs.python.org/3/library/pathlib.html Answer from Deleted User on reddit.com
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_file_write.asp
Python File Write
Note: If the file already exists, an error will be raised. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com ยท If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com ยท HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ writing-to-file-in-python
Writing to file in Python - GeeksforGeeks
Before writing to a file, letโ€™s first understand the different ways to create one. Creating a file is the first step before writing data. In Python you control creation behaviour with the mode passed to open() (or with pathlib helpers). Note: You can combine flags like "wb" (write + binary) or "a+" (append + read).
Published ย  April 4, 2026
Discussions

Writing to file using Python - Stack Overflow
I have a file called output.txt, which I want to write into from a few functions around the code, some of which are recursive. Problem is, every time I write I need to open the file again and again... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Two ways of saving output to a file. Which one is better ? and why?
Whatโ€™s the proper way of saving an output to a text file ? Both codes give the same result. file1 = open('output_test1.txt', 'w') for x in range(9): print(x, file =file1) file1 = open('output_test2.txt', 'w') for x in range(9): file1.write(str(x) + '\n') More on discuss.python.org
๐ŸŒ discuss.python.org
14
0
April 30, 2023
Write to the file not working
MyFavoriteColors content: red yellow green blue Prob: Replace a single line If the user wants to replace a single line in the file, they will then need to be prompted for 2 bits of information: The line number they want to update. The text that should replace that line. x = int(input("Enter ... More on discuss.python.org
๐ŸŒ discuss.python.org
4
0
May 18, 2021
Writing a for loop to a excel file

You could use a comma separated value to store the table.

More on reddit.com
๐ŸŒ r/Python
6
1
August 24, 2017
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how does one read and write to files in python?
r/learnpython on Reddit: How does one read and write to files in python?
February 24, 2021 -

I have watched many a YouTube video, but alas, it just confused me more. What is the python equivalent to things like File.WriteLine in c#?

Thanks in advance.

Top answer
1 of 4
3
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
2 of 4
2
Firstly, you have to open a file. You can do so with the built-in open() function. This function can take a few optional arguments, but the one argument you have to provide is the filename or path to the file. You should also consider the mode that you would like to open the file in. The default is read mode "r". In this mode you can pull information from the file, but you cannot write to it. Other useful modes include write mode "w", append mode "a", read-and-write mode "r+", read-and-write mode with truncation (see the next sentence) "w+", and binary read mode "rb". Note that both "w" and "w+" modes will blank out (AKA "truncate to 0") your file if it already exists so be careful using them. You can see all of the options in the documentation . So let's say you wanted to open a text file in write mode. You would do so with the line file_obj = open("/path/to/file", mode="w") From here you have a few options to write to the file. The easiest is the write() method. Here's an example use. file_obj.write("I taste a liquor never brewed\n") file_obj.write("From Tankards scooped in Pearl\n") file_obj.write("Not all the Frankfort Berries\n") file_obj.write("Yield such an Alcohol!") Notice that I have to end each line with a newline character \n because unlike say the print() function, write() does not automatically append a newline. Note however, that Python will often wait until it is "sure" that you are done writing to the file before actually pushing the text into the file. Until then it is stored in a buffer. The easiest way to ensure this happens is to close the file as soon as you are done with it. file_obj.close() Note that it is also useful to close a file opened in read mode if your program is going to be running for a while (for example, if it's running on a server) so that you also let Python's garbage collector clean up some memory required to keep the file open. Hence, when you open a file, you will almost always want to close it afterward. Since it is a very common error to forget to add that close() call, Python has our backs with an alternate way to both open and close a file. It's called a context manager and the syntax looks like this. with open("/path/to/file", mode="w") as file_obj: file_obj.write("I taste a liquor never brewed\n") file_obj.write("From Tankards scooped in Pearl\n") file_obj.write("Not all the Frankfort Berries\n") file_obj.write("Yield such an Alcohol!") # let's check if the file is still open print(file_obj.closed) # now let's check outside of the context manager print(file_obj.closed) Note that this is especially useful because that call to close the file will even get run if a runtime exception occurs. Reading a file has its own methods. Let's assume we've run the above code and created a file (make sure that you fill in "/path/to/file" with a filename that didn't previously exist before you run that code). Then we can read the whole thing into a string using the read() method. with open("/path/to/file") as file_obj: contents = file_obj.read() print(contents) We can instead read the file into a list of strings -- one for each line -- with the readlines() method or get just the next (starting with the first) line with readline(). I encourage you to test both of those methods out. However, one other very useful method of reading files in one line at a time is to use a for loop. with open("/path/to/file") as file_obj: for line in file_obj: print(line, end="") Exercise for the reader: see if you can reason out why I left out the mode argument to open() and why I specified end="" in the print() function based on what I've said so far. One final note: if you plan to do anything else to the file -- for example, renaming it, moving it, verifying it exists before opening it, etc -- then you can use the Path.open () method instead of the regular ol' open() function. Here's an example. from pathlib import Path file = Path("path/to/file") with file.open() as file_obj: for line in file_obj: print(line, end="") # and now that I've closed the file I can rename it or whatever References: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open https://docs.python.org/3/library/pathlib.html
๐ŸŒ
CodingNomads
codingnomads.com โ€บ python-write-to-file
Python: Write to File
Edit the desktop file counter script that you built in the previous section to write its output to a file. Run the script and confirm that you can read the output in your new file. Take a new screenshot or add another file to your desktop, then run the script again. ... In a future lesson, you'll learn how you can improve this. You can use Python to write data to a file to persist the information after your script has finished running.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Two ways of saving output to a file. Which one is better ? and why? - Python Help - Discussions on Python.org
April 30, 2023 - Whatโ€™s the proper way of saving an output to a text file ? Both codes give the same result. file1 = open('output_test1.txt', 'w') for x in range(9): print(x, file =file1) file1 = open('output_test2.txt', 'w') for x in range(9): file1.write(str(x) + '\n')
Find elsewhere
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ creating-and-writing-file-python
Write to a file in Python - Python Morsels
October 18, 2021 - To write to a file in Python, you can use the built-in open function, specifying a mode of w or wt and then use the write method on the file object.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ file-handling-in-python
File Handling in Python โ€“ How to Create, Read, and Write to a File
August 26, 2022 - But if you retry the code above ... an error notifying you that the file already exists. It'll look like the image below: "w" โ€“ Write: this command will create a new text file whether or not there is a file in the memory with ...
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ fundamentals-of-text-data-manipulation โ€บ lessons โ€บ writing-to-files-in-python
Writing to Files in Python
The with keyword ensures that the file is closed automatically after writing. Then, we can write to the file using the write() method.
๐ŸŒ
LearnPython.com
learnpython.com โ€บ blog โ€บ write-to-file-python
How to Write to File in Python | LearnPython.com
Discover how to write to a file in Python using the write() and writelines() methods and the pathlib and csv modules.
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-file.html
File Read Write
Instead of coding the file-writing in your program, there is an alternative in the terminal that handles simple cases easily. This feature works in Mac, Windows, and Linux. Many programs print output to standard output. When you run the program in the terminal, you see this printed out right there, like this run of a super.py program that prints out that today is just great. $ python3 super.py Everything today is just super Most excellent $ What if we wanted to write that text to an out.txt file?
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ write one or more lines to a file in python
Python Write Multiple Lines to File With writelines | Sentry
3 weeks ago - With the file open, we call f.write() with the line to write. We conclude the line with a newline character, \n. You may have heard that line terminators differ between operating systems โ€“ Unix-based systems use \n, whereas Microsoft Windows uses \r\n. Fortunately, Python abstracts this detail ...
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ inputoutput.html
7. Input and Output โ€” Python 3.14.6 documentation
So far weโ€™ve encountered two ways of writing values: expression statements and the print() function. (A third way is using the write() method of file objects; the standard output file can be referenced as sys.stdout.
๐ŸŒ
Quora
quora.com โ€บ How-do-you-open-write-and-close-a-file-in-Python
How to open, write and close a file in Python - Quora
Answer (1 of 2): You can use the [code ]open()[/code] function. For example: [code]PATH = r"C:\Users\USER\Documents\myfile.txt" file = open(PATH, "r") contents = file.read() file.close() [/code]The first argument of [code ]open()[/code] is the path of the file, and the second argument is the mod...
๐ŸŒ
University of Pittsburgh
sites.pitt.edu โ€บ ~naraehan โ€บ python3 โ€บ mbb13.html
Python 3 Notes: Writing Text to a File
Python 3 Notes [ HOME | LING 1330/2330 ] Tutorial 13: Writing Text to a File << Previous Tutorial Next Tutorial >> On this page: writing to a file, open('...', 'w'), .writelines(), .close(). Video Tutorial Python 3 Changes NONE! Python 2 vs. 3 Summary ยท Video Summary Writing a file within ...
๐ŸŒ
Compciv
compciv.org โ€บ guides โ€บ python โ€บ fileio โ€บ open-and-write-files
Opening files and writing to files | Computational Methods in the Civic Sphere at Stanford University
Chapter 11. Files [Mark Pilgrim; Dive into Python 3] Python Input and Output Tutorial [Python Documentation] There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ errors.html
8. Errors and Exceptions โ€” Python 3.14.6 documentation
If you need to determine whether an exception was raised but donโ€™t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception: >>> try: ... raise NameError('HiThere') ... except NameError: ... print('An exception flew by!') ... raise ... An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in <module> raise NameError('HiThere') NameError: HiThere
๐ŸŒ
Quora
quora.com โ€บ How-do-you-open-and-write-to-a-file-in-Python
How to open and write to a file in Python - Quora
Answer (1 of 3): 1. Read Only (โ€˜rโ€™) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened. 2. Read and Write (โ€˜r+โ€™) : Open the file for reading and writing.
๐ŸŒ
TecAdmin
tecadmin.net โ€บ python-write-file
Python: Write to File โ€“ TecAdmin
April 26, 2025 - One of the simplest ways to write to a file in Python is using the `write()` method of a file object. To use the `write()` method, you first need to open the file in write mode using the `open()` function.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Write to the file not working - Python Help - Discussions on Python.org
May 18, 2021 - MyFavoriteColors content: red yellow green blue Prob: Replace a single line If the user wants to replace a single line in the file, they will then need to be prompted for 2 bits of information: The line number they want to update. The text that should replace that line. x = int(input("Enter line number to change: ")) y = input("Enter color: ") BrightColor = open("MyFavoriteColors", "r") lines = BrightColor.readlines() lines[x] = y print(lines) Br...