Summary: In this tutorial, you will learn different ways to edit, write, append text to a file using Python programming language.

In Python, you can easily append, delete or overwrite a file. But when you write to a file in Python, text cannot be inserted into the middle of a file, therefore will require rewriting it.

Let’s see different ways to edit a file in Python.

Use writelines() or write() to Write to File in Python

# Open file for writing
my_file = open("my_file.txt", "w")

# Write to File
my_file.write("Hello\n")
my_file.write("Welcome to PencilProgrammer.com")


# Read the file's entire content

my_file = open("my_file.txt")
content = my_file.read()

# Close file after editing
my_file.close()

print(content)

Output:

Hello
Welcome to PencilProgrammer.com

In this method, we have opened the file in write mode with open(file, mode="w") method.

The second parameter in open method call is the mode. Set mode to "w" to write to a file or "a" to append to the end of a file. Setting mode to w will create the file specified if it does not exist, and overwrite the file if it does exist.

After the open statement, we have used file.write(s) to write the strings into the file. This method writes the specified string into the file and returns the number of characters written.

You can also use file.writelines(lines) to write multiple lines of text to a file by specifying the strings to add as a sequence such as a list or tuple.

For example, in the following program we are writing strings using the file.writelines(lines) method:

# Open file for writing
my_file = open("my_file.txt", "w")

# Write Strings to File
text_list = ["My\n", "Name\n", "is Adarsh"]
my_file.writelines(text_list)

# Read the file's entire content
my_file = open("my_file.txt")
content = my_file.read()

# Close file after editing
my_file.close()

print(content)

Output:

My
Name
is Adarsh

Use file.seek() to Prepend to File

# Set file’s current position to the beginning
content = my_file.read()
my_file.seek(0)

# Prepend the String
my_file = open("my_file.txt", "w")
my_file.write("Hi, Good Morning.\n" + content)


# Read the file's entire content and close
my_file = open("my_file.txt")
content = my_file.read()
my_file.close()

print(content)

Output:

Hi, Good Morning.
My
Name
is Adarsh

In this program, we used the file.seek(0) to set the file’s current position at the beginning of the file to prepend a new string.

First, we read the file’s entire content and store it in content variable. Then, we rewind the file to the beginning of the file using file.seek(offset) by setting offset to 0.

Lastly, we prepend the string to add to the previously stored text from the file and write it to the file.

In this example, we opened the file with mode set to "w+" which allows both read and write access, but also overwrites the file if it exist.

Note: When reading or writing, the position of the file changes, so use the seek() method whenever you want to reset the position to the beginning of the file.

Use files.readlines() to Edit a File

my_file = open("my_file.txt")

# Get file's content as a list
string_list = my_file.readlines()

my_file.close()
print(string_list)

Output:

[‘Hi, Good Morning.\n’, ‘My\n’, ‘Name\n’, ‘is Adarsh’]

Here, we have used file.readlines() to get a list of strings with each string as a line from my_file.txt.

Now, we can edit this list by deleting or adding a line. To delete a line, remove an item from the list and to add a line, add an item to the list.

When done, use string.join(iterable) with the list of strings as iterable to convert to a single string. Then write this string back to the file by calling file.write(s) with s as the string.

Here is an example of editing a file:

string_list[3] = "is Pencil Programmer.\n"

# Convert `string_list` to a single string
new_file_contents = "".join(string_list)

# Write to File
my_file = open("data.txt", "w")
my_file.write(new_file_contents)
my_file.close()

# Read the updated file
readable_file = open("data.txt")
read_file = readable_file.read()
print(read_file)

# Close file after editing
my_file.close()

Output:

Hi, Good Morning.
My
Name
is Pencil Programmer.

So, these were the ways using which you easily edit, write, prepend, append or rewind a file in Python.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply