Python write file not overwrite

Python File Handling

Python provides a wide range of built-in functions for file handling. It makes it really easy to create, update, read, and delete files.

Open a File

When you want to work with a file, the first thing to do is to open it. You can open a file using open() built-in function specifying its name.

When you specify the filename only, it is assumed that the file is located in the same folder as Python. If it is somewhere else, you can specify the exact path where the file is located.

f = open(r'C:\Python33\Scripts\myfile.txt')

Remember! While specifying the exact path, characters prefaced by \ (like \n \r \t etc.) are interpreted as special characters. You can escape them using:

Specify File Mode

Here are five different modes you can use to open the file:

Python File Modes

Character Mode Description
‘r’ Read (default) Open a file for read only
‘w’ Write Open a file for write only (overwrite)
‘a’ Append Open a file for write only (append)
‘r+’ Read+Write open a file for both reading and writing
‘x’ Create Create a new file
Читайте также:  Html with java swing

You can also specify how the file should be handled.

Python File Modes

Character Mode Description
‘t’ Text (default) Read and write strings from and to the file.
‘b’ Binary Read and write bytes objects from and to the file.This mode is used for all files that don’t contain text (e.g. images).
# Open a file for reading f = open('myfile.txt') # Open a file for writing f = open('myfile.txt', 'w') # Open a file for reading and writing f = open('myfile.txt', 'r+') # Open a binary file for reading f = open('myfile.txt', 'rb')

Because read mode ‘r’ and text mode ‘t’ are default modes, you do not need to specify them.

Read a File

Suppose you have the following file.

First line of the file. Second line of the file. Third line of the file.

To read its contents, you can use read() method.

# Read entire file f = open('myfile.txt') print(f.read()) # Prints: # First line of the file. # Second line of the file. # Third line of the file.

By default, the read() method reads the entire file. However, you can specify the maximum number of characters to read.

f = open('myfile.txt') print(f.read(3)) # Prints Fir print(f.read(5)) # Prints First

Read Lines

To read a single line from the file, use readline() method.

f = open('myfile.txt') print(f.readline()) # Prints First line of the file. # Call it again to read next line print(f.readline()) # Prints Second line of the file.

You can loop through an entire file line-by-line using a simple for loop.

f = open('myfile.txt') for line in f: print(line) # Prints: # First line of the file. # Second line of the file. # Third line of the file.

If you want to read all the lines in a file into a list of strings, use readlines() method.

# Read all the lines in a file into a list of strings f = open('myfile.txt') print(f.readlines()) # Prints: # ['First line of the file.\n', 'Second line of the file.\n', 'Third line of the file.']

Note that list(f) gives the same result as readlines()

Write a File

Use the write() built-in method to write to an existing file. Remember that you need to open the file in one of the writing modes (‘w’, ‘a’ or ‘r+’) first.

Write mode ‘w’

In ‘w’ mode the entire contents of the file are overwritten:

f = open('myfile.txt', 'w') f.write('Overwrite existing data.')

Append mode ‘a’

In ‘a’ mode, text is added to the end of the file:

f = open('myfile.txt', 'a') f.write(' Append this text.')
First line of the file. Second line of the file. Third line of the file. Append this text.

Read-write mode ‘r+’

In ‘r+’ mode, the file is partially overwritten:

f = open('myfile.txt', 'r+') f.write('---Overwrite content---')
---Overwrite content--- Second line of the file. Third line of the file.

Write Multiple Lines

To write multiple lines to a file at once, use writelines() method. This method accepts list of strings as an input.

f = open('myfile.txt', 'w') lines = ['New line 1\n', 'New line 2\n', 'New line 3'] f.writelines(lines)
New line 1 New line 2 New line 3

Flush Output Buffer

When you write to a file, the data is not immediately written to disk instead it is stored in buffer memory. It is written to disk only when you close the file or manually flush the output buffer.

# Flush output buffer to disk without closing f = open('myfile.txt', 'a') f.write('Append this text.') f.flush()

Close a File

It’s a good practice to close the file once you are finished with it. You don’t want an open file running around taking up resources!

Use the close() function to close an open file.

f = open('myfile.txt') f.close() # check closed status print(f.closed) # Prints True

There are two approaches to ensure that a file is closed properly, even in cases of error.

The first approach is to use the with keyword, which Python recommends, as it automatically takes care of closing the file once it leaves the with block (even in cases of error).

with open('myfile.txt') as f: print(f.read())

The second approach is to use the try-finally block:

f = open('myfile.txt') try: # File operations goes here finally: f.close()

Create a New File

If you try to open a file for writing that does not exist, Python will automatically create the file for you.

# Create a file and open it for writing # write mode f = open('newFile.txt', 'w') # append mode f = open('newFile.txt', 'a') # read + write mode f = open('newFile.txt', 'r+')

There is another way to create a file. You can use open() method and specify exclusive creation mode ‘x’.

# Create a file exclusively f = open('newFile.txt', 'x')

Note that when you use this mode, make sure that the file is not already present, if it is, Python will raise the error.

Delete a File

You can delete a file by importing the OS module and using its remove() method.

import os os.remove('myfile.txt')

Check if File Exists

If you try to open or delete a file that does not exist, an error occurs. To avoid this, you can precheck if the file already exists by using the isfile() method from the OS module.

import os if os.path.isfile('myfile.txt'): f = open('myfile.txt') else: print('The file does not exist.') 

Random Access

Sometimes you need to read from the record in the middle of the file at that time you can use the seek(offset, from_what) method. This function moves the file pointer from its current position to a specific position.

The offset is the number of characters from the from_what parameter which has three possible values:

  • 0 – indicates the beginning of the file (default)
  • 1 – indicates the current pointer position
  • 2 – indicates the end of the file

Suppose you have the following file.

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Here’s how you can use the seek() method to randomly access the contents of a file.

f = open('myfile.txt', 'rb+') # go to the 7th character and read one character f.seek(6) print(f.read(1)) # Prints G # go to the 3rd character from current position (letter G) f.seek(3, 1) print(f.read(1)) # Prints K # go to the 3rd character before the end f.seek(-3, 2) print(f.read(1)) # Prints X

For Python 3.2 and up, in text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed.

In order to use seek from current position and end, you have to open the text file in binary mode.

If you want to check the current position of the file pointer, use the tell() method.

f = open('myfile.txt') # initial position print(f.tell()) # Prints 0 # after reading 5 characters f.read(5) print(f.tell()) # Prints 5

Источник

How to Use Python to Write a Text File (.txt)

How to Use Python to Write a Text File (txt) Cover Image

In this tutorial, you’ll learn how to use Python to write (or save) to a text file. Python provides incredible opportunity to read and work with text files – being able to save the output to a text file is an important skill. Python can handle both regular text files and binary files – in this tutorial, you’ll learn how to work with text files.

By the end of this tutorial, you’ll have learned:

  • How to use Python to write to a .txt file
  • How to use a context manager to safely write to a text file
  • How to append text to a file in Python
  • How to write UTF-8 text to a File in Python

How to Use Python to Write to a Text File

Python provides a number of ways to write text to a file, depending on how many lines you’re writing:

  • .write() will write a single line to a file
  • .writelines() will write multiple lines to a file

These methods allow you to write either a single line at a time or write multiple lines to an opened file. While Python allows you to open a file using the open() , it’s best to use a context manager to more efficiently and safely handle closing the file.

Let’s see what this looks like:

# Writing a Single Line to a Text File text = 'Welcome to datagy.io!' with open('/Users/nikpi/Desktop/textfile.txt', 'w') as f: f.write(text)

Let’s break down what the code above is doing:

  • We load a string that holds our text in a variable text
  • We then use a context manager to open a file in ‘w’ mode, which allows us to overwrite an existing text
  • The file doesn’t need to exist – if it doesn’t, it’ll automatically be created
  • When then use the .write() method to write our string to the file

Writing Multiple Lines to a Text File Using Python

In many cases, you may not want to write a single line of text to a file. Let’s take a look at how we can write multiple lines of text to a file using the .write() method:

# Writing Multiple Lines to a Text File text = ['Welcome to datagy.io!', "Let's learn some Python!"] with open('/Users/nikpi/Desktop/textfile.txt', 'w') as f: for line in text: f.write(line) f.write('\n')

Let’s take a look at what we’re doing in the code above:

  • We load a list of strings that contains the lines of text we want to save
  • Similar to the previous example, we open the file using a context manager
  • We then loop over each item in the list to write each string to the file
  • For each item, we also write a newline character so that each line is split across a new line

The approach above feels a bit clunky. We can simplify this process by using the .writelines() method, which allows us to write multiple lines at once. Let’s see how we can modify our code above to use the .writelines() method:

# Writing Multiple Lines to a Text File (with .writelines) text = ['Welcome to datagy.io', "Let's learn some Python!"] with open('/Users/nikpi/Desktop/textfile.txt', 'w') as f: f.writelines('\n'.join(text))

In the code above, we avoid using a for loop to write multiple lines of text to a file. Because our text isn’t separated by newline characters, we use the .join() string method to place each item onto a new line.

How to Append to a Text File in Python

In the previous sections, you learned how to write a new file with text in Python. In this section, you’ll learn how to append to a given text file using Python. We previously used the write mode, ‘w’ when opening the file – in order to append, we use the append mode, ‘a’ .

Let’s see how we can append to a text file in Python:

# Appending to a Text File in Python text = 'Welcome to datagy.io!\n' with open('/Users/nikpi/Desktop/textfile.txt', 'a') as f: f.write(text)

Running this will append to the end of the text file. Note that we applied the newline character into the string. This could also be done in the context manager, depending on how you prefer your code to run.

Similarly, we can append multiple lines to a file by using the .writelines() method, as shown below:

# Appending Multiple Lines to a Text File text = ['Welcome to datagy.io!\n', 'Python is fun!\n'] with open('/Users/nikpi/Desktop/textfile.txt', 'a') as f: f.writelines(text)

How to Write UTF-8 Encoded Text to a File in Python

Python will open a file using the system’s default encoding. While UTF-8 is the de-facto standard, your system may not open the file using that encoding format. Because of this, you may need to specify the encoding format when opening the file.

Let’s see how we can do this:

# Specifying Encoding to UTF-8 text = 'é' with open('/Users/nikpi/Desktop/textfile.txt', 'w', encoding="utf-8") as f: f.write(text)

Running this code on, for example, macOS, doesn’t require specifying the encoding. However, if you want your code to run platform independently, it is a good idea to specify the encoding.

Conclusion

In this tutorial, you learned how to use Python to write a text file. You first learned about the different ways of overwriting a file using the .write() and .writelines() methods. You learned about the nuances of inserting newline characters. Then, you learned how to append to an existing file, both single lines as well as multiple lines. Finally, you learned how to specify the encoding when writing a file.

Additional Resources

To learn more about related topics, check out the tutorials below:

Источник

Оцените статью