This should be as simple as:

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

From The Documentation:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

Some useful reading:

  • The with statement
  • open()
    • 'a' is for append, or use
    • 'w' to write with truncation
  • os (particularly os.linesep)
Answer from johnsyweb on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › inputoutput.html
7. Input and Output — Python 3.14.4 documentation
In text mode, the default when reading is to convert platform-specific line endings (\n on Unix, \r\n on Windows) to just \n. When writing in text mode, the default is to convert occurrences of \n back to platform-specific line endings. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE files.
Discussions

Understanding .write line
outputFile.write("%-20s.2f\n" % ("Total:", total)) Would anybody mind breaking down the above line? I understand these parts: outputFile.write: writes text into a .txt document named earlier ... .2f\n" adds 2 decimal points to the end of the float number that’s outputted (“Total:”, total) ... More on discuss.python.org
🌐 discuss.python.org
5
0
November 25, 2021
Need help with my code. Adding a line of text in the middle of a file.
Simultaneous reading and writing a file almost never works in the general case and is rarely used in practice. The correct approach is to open two files, one being your input file and the other is a temporary output file. You read the input file and copy each line to the output file until you find the line of interest. Then you write the new line to the output file. Finally, copy all the remaining lines from the input file to the output file. Close both files and then rename the output file to the same pathname as the input file. Update: In your particular case, if the file is small, open the file for reading, read all the file into a list of strings and close the file. Reopen the file for writing and write the list of strings into the output file, adding extra lines as you go, then close the file. This is not as robust as the rename approach above, and any crash during the writing leaves you with a corrupt file plus you have lost the original input file. More on reddit.com
🌐 r/learnpython
8
5
May 7, 2024
Open a txt file with w and write lines?
Post your code. More on reddit.com
🌐 r/learnpython
8
1
October 31, 2022
How to write file with multiple lines
In short, you put in newline characters (\n). If you post your code, we can be a lot more specific. More on reddit.com
🌐 r/learnpython
5
4
September 27, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › computer science fundamentals › difference-between-write-and-writelines-function-in-python
Difference between write() and writelines() function in Python - GeeksforGeeks
July 23, 2025 - # write all the strings present in the list "list_of_lines" # referenced by file object. file_name.writelines(list_of_lines) As per the syntax, the list of strings that is passed to the writelines() function is written into the opened file. Similar to the write() function, the writelines() function does not add a newline character(\n) to the end of the string. Example: Python3 ·
🌐
Sentry
sentry.io › sentry answers › python › write one or more lines to a file in python
Write one or more lines to a file in Python | Sentry
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 and we can just use \n regardless of our operating system.
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-file.html
File Read Write
This is handy if the code does not need to consider each line separately. with open(filename) as f: text = f.read() # Look at text str · In this example text is the string 'Roses are red\nViolets are blue\n' — the whole contents of the file in one string. This approach will require memory in Python to store all of the bytes of the file.
🌐
GeeksforGeeks
geeksforgeeks.org › python › writing-to-file-in-python
Writing to file in Python - GeeksforGeeks
4 days ago - Python provides two common approaches: writelines() for lists of strings and join() for building a single text block. Example 1: This writes a list of lines; each element includes a \n.
Find elsewhere
🌐
W3Schools
w3schools.com › python › python_file_write.asp
Python File Write
Python Functions Python Arguments Python *args / **kwargs Python Scope Python Decorators Python Lambda Python Recursion Python Generators Code Challenge Python Range ... Matplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib ...
🌐
Tutorialspoint
tutorialspoint.com › python › file_writelines.htm
Python File writelines() Method
The Python File writelines() method writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. When the method writes the sequence of strings into this file, it is first written
🌐
ThePythonGuru
thepythonguru.com › python-how-to-read-and-write-files › index.html
Python: How to read and write files - ThePythonGuru.com
January 7, 2020 - You can also append the newline to the line using the print() function, as follows: Here is an example of writelines() method.
🌐
Reddit
reddit.com › r/learnpython › need help with my code. adding a line of text in the middle of a file.
r/learnpython on Reddit: Need help with my code. Adding a line of text in the middle of a file.
May 7, 2024 -

Hey everyone, I have been trying to figure out how to do this for a few days now and keep coming up short. I must be missing something but cant figure out what. I am trying to write a script that will open and search a document line by line and if it finds a specific line of text it will add a new line of text underneath it. Ive gone through a few iterations and this is the closest Ive got, but its still not working.

I thought it would overwrite what was already in the text file with what I have stored in outLine, but it seems to be appending outLine to the end of the text already in the file.

Here is my code so far:

fileName =  "C:\\user\\Test\\helloWorld.txt"
aboveText = "How are you today?"
newText = "Added line in the middle"

with open(fileName, "r+") as file:
    outLine = ""
    for line in file.readlines():
        if line == aboveText + "\n":
            outLine += aboveText + "\n" + newText + "\n"
        else:
            outLine += line
    file.write(outLine)

File Before the edit:
Hello world!
How are you today?
add one line here
add one line here

How I want it to look:
Hello world!
How are you today?
Added line in the middle
add one line here
add one line here

How its coming out with my code:
Hello world!
How are you today?
add one line here
add one line hereHello world!
How are you today?
Added line in the middle
add one line here
add one line here

Top answer
1 of 5
3
Simultaneous reading and writing a file almost never works in the general case and is rarely used in practice. The correct approach is to open two files, one being your input file and the other is a temporary output file. You read the input file and copy each line to the output file until you find the line of interest. Then you write the new line to the output file. Finally, copy all the remaining lines from the input file to the output file. Close both files and then rename the output file to the same pathname as the input file. Update: In your particular case, if the file is small, open the file for reading, read all the file into a list of strings and close the file. Reopen the file for writing and write the list of strings into the output file, adding extra lines as you go, then close the file. This is not as robust as the rename approach above, and any crash during the writing leaves you with a corrupt file plus you have lost the original input file.
2 of 5
2
Its been a long time since I worked with a basic text file but I think the behavior you are seeing is due to how you are opening the file in "r+" mode. https://docs.python.org/3/library/functions.html#open mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation, and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform-dependent: locale.getencoding() is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are: Character | Meaning | 'r' | open for reading (default) | 'w' | open for writing, truncating the file first | 'x' | open for exclusive creation, failing if the file already exists | 'a' | open for writing, appending to the end of file if it exists | 'b' | binary mode | 't' | text mode (default) | '+' | open for updating (reading and writing) The default mode is 'r' (open for reading text, a synonym of 'rt'). Modes 'w+' and 'w+b' open and truncate the file. Modes 'r+' and 'r+b' open the file with no truncation. As mentioned in the Overview , Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str , the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.
🌐
freeCodeCamp
freecodecamp.org › news › file-handling-in-python
File Handling in Python – How to Create, Read, and Write to a File
August 26, 2022 - In Python, there are six methods or access modes, which are: Read Only ('r’): This mode opens the text files for reading only. The start of the file is where the handle is located. It raises the I/O error if the file does not exist. This is the default mode for opening files as well. Read and Write ('r+’): This method opens the file for both reading and writing.
🌐
W3Schools
w3schools.com › python › ref_file_writelines.asp
Python File writelines() Method
Python File Handling Python Read Files Python Write/Create Files Python Delete Files · NumPy Tutorial Pandas Tutorial SciPy Tutorial Django Tutorial · Matplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib Labels Matplotlib Grid Matplotlib Subplot Matplotlib Scatter Matplotlib Bars Matplotlib Histograms Matplotlib Pie Charts ·
🌐
Reddit
reddit.com › r/learnpython › how to write file with multiple lines
r/learnpython on Reddit: How to write file with multiple lines
September 27, 2023 -

I have several input commands and file write commands to write those inputs into a file. The problem is that when there is multiple input, the files just put all of them next to each other on the same line, even with append. How can I make it so that there are many lines in the file?

🌐
Spark By {Examples}
sparkbyexamples.com › home › python › different ways to write line to file in python
Different ways to Write Line to File in Python - Spark By {Examples}
May 31, 2024 - # Example 1: Writing a text line with open("file.txt", 'w', encoding='utf-8') as file: line_to_write = "This is a line of text." file.write(line_to_write + '\n') # Example 2: Writing a numeric line with open("file.txt", 'w', encoding='utf-8') ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-write-a-single-line-in-text-file-using-python
How to write a single line in text file using Python?
May 11, 2023 - To write into a file using append mode, open the file in append mode, with either 'a' or 'a+' as the access mode, to append a new line to an existing file. The following are the definitions of these access modes: Only append ('a'): To begin writing, open the file.
🌐
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.
🌐
Python.org
discuss.python.org › ideas
Having a `writeline` method on appropriate `io` objects - Ideas - Discussions on Python.org
February 3, 2020 - Writing a string terminated with a newline seems to be a very common operation in file I/O, so a writeline convenience method seems like it would be an useful addition to the language. From a quick “what do you think” po…