Как дополнять файл python

How to Write to File in Python

Before diving into the nitty-gritty of how to write to file in Python, I want to mention that I use Python 3.8.5 and Windows 10. However, your results should be the same on any operating system.

It’s good to have some knowledge of file manipulation before you read this article. For more information, read How to Work with Files and Directories in Python and How to Rename Files with Python.

There are multiple ways to write to files and to write data in Python. Let’s start with the write() method.

Use write() to Write to File in Python

The first step to write a file in Python is to open it, which means you can access it through a script. There are two ways to open a file. The first one is to use open() , as shown below:

# open the file in the write mode f = open('file.txt', 'w')

However, with this method, you need to close the file yourself by calling the close() method:

It is shorter to use the with statement, as we do not need to call the close() method.

This is the method we’ll use in this tutorial:

with open("file.txt", "w") as file:

The above line of code will open file.txt and will assign the file handler to the variable called file .

We can then call the write() method to modify our file programmatically.

file.write("Python is awesome!")

Once this command has been executed, we want to read the file to see if it has been updated. We need to call the read() method, as shown below:

# Open and read the file after writing: with open("file.txt", "r") as file: print(file.read())

It’s important to note that the parameters in the open() function will decide where the write() method will be active.

If you want to learn more on how to write files in Python with the write() method, check out our course on Working with Files and Directories in Python.

Use writelines() to Add List Data to a File

Another method that you can use is writelines() . This method adds terms of a list in a programmatic way. Let’s run an example:

# open file with open("file2.txt", "a") as file: # write to file file.writelines(["Hey there!", "LearnPython.com is awesome!"]) #open and read the file after the appending: with open("file2.txt", "r") as file: print(file.read())

After checking the output, you will notice that writelines() does not add any line separators by default; we have to specify the line separator. We can modify our code with the following:

# open and write to file with open("file2.txt", "a") as file: file.writelines(["Hey there!\n", "LearnPython.com is awesome!\n"]) # open and read the file after the appending: with open("file2.txt", "r") as file: print(file.read())

A more Pythonic and efficient way of doing it is:

# open file with open("file2.txt", "a") as file: # set a list of lines to add: lines = ["Hey there!", "LearnPython.com is awesome!"] # write to file and add a separator file.writelines(s + '\n' for s in lines) #open and read the file after the appending: with open("file2.txt", "r") as file: print(file.read())

The code above will use new lines as the line separator.

Читайте также:  Html for float right

Writing Data to CSV Files in Python

You might find it useful to be able to update a CSV file directly with Python.

CSV stands for comma-separated values. If you are a data professional, you’ve certainly come across this kind of file. A CSV file is a plain text file containing a list of data. This type of file is often used to exchange data between applications. If you want to refresh your knowledge of CSV files, read our article How to Read CSV Files in Python.

In this part, we will use Python’s built-in csv module to update a CSV file.

When you want to write data to a file in Python, you’ll probably want to add one or more rows at once. The data can be stored in lists or a dictionary. Let’s explore some ways to write data to files in Python.

Writing List Data to a CSV

Let’s explore how to add a single row of data with writerow() and multiple rows of data with writerows() .

Use writerow() for a Single Row

To write in a CSV file, we need to open the file, create a writer object and update the file. Let’s run an example:

# import import csv # Create header and data variables header = ['last_name', 'first_name', 'zip_code', 'spending'] data = ['Doe', 'John', 546000, 76] with open('customers.csv', 'w', encoding='UTF8', newline='') as file: # Create a writer object writer = csv.writer(file) # Write the header writer.writerow(header) # Write the data writer.writerow(data)

For detailed information, it’s always a good idea to read the documentation.

Now, let’s explore how to write data in Python when you need to add multiple rows of data.

Use writerows() for Multiple Rows

We can write multiple rows to a file using the writerows() method:

# import import csv # Create header and data variables header = ['last_name', 'first_name', 'zip_code', 'spending'] data = [ ['Smith', 'Nicholas', 453560, 82], ['Thompson', 'Julia', 326908, 143], ['French', 'Michael', 678321, 189], ['Wright', 'Eva', 285674, 225], ['White', 'David', 213456, 167] ] with open('customers.csv', 'w', encoding='UTF8', newline='') as file: # Create a writer object writer = csv.writer(file) # Write the header writer.writerow(header) # Add multiple rows of data writer.writerows(data)

We just added several rows to our file.

You can find more information about the writerows() method in the documentation.

Writing Dictionary Data to a CSV

If each row of the CSV file is a dictionary, you can update that file using the csv module’s dictWriter() function. For example:

# import import csv # csv header fieldnames = ['last_name', 'first_name', 'zip_code', 'spending'] # csv data rows = [< 'last_name': 'bloggs', 'first_name': 'Joe', 'zip_code': 986542, 'spending': 367 >,< 'last_name': 'Soap', 'first_name': 'Bob', 'zip_code': 567890, 'spending': 287 >,< 'last_name': 'farnsbarns', 'first_name': 'Charlie', 'zip_code': 123456, 'spending': 245 >] with open('customers.csv', 'w', encoding='UTF8', newline='') as f: # Create a writer object writer = csv.DictWriter(f, fieldnames=fieldnames) # Write header writer.writeheader() # Write data from dictionary writer.writerows(rows)

And that’s all you have to do!

If you want to learn more on the topic, do not forget to check the course on working with files and directories in Python.

Using pathlib to Write Files in Python

Now let’s explore using the pathlib module to write to a file in Python. If you are not familiar with pathlib, see my previous article on file renaming with Python.

Читайте также:  How to select an option in php

It is important to note that pathlib has greater portability between operating systems and is therefore preferred.

Use write_text()

We can use the Path().write_text() method from pathlib to write text to a file.

First, we use the Path class from pathlib to access file.txt , and second, we call the write_text() method to append text to the file. Let’s run an example:

# import from pathlib import Path # Open a file and add text to file Path('file.txt').write_text('Welcome to LearnPython.com')

Next, we’ll use the is_file() , with_name() and with_suffix() functions to filter the files we want to update. We will only update those files that fulfill certain conditions.

The is_file() function will return a Boolean value that’s True if the path points to a regular file and False if it does not. The with_name() function will return a new path with the changed filename. Finally, with_suffix() will create a new path with a new file extension.

You can read about the details of these methods in the Python documentation.

Let’s run an example that demonstrates all this. We will open our text file, write some text, rename the file, and save it as a CSV file.

# import from pathlib import Path # set the directory path = Path.cwd() / 'file.txt' # Check if the file is a file if path.is_file(): # add text path.write_text('Welcome to LearnPython.com') # rename file with new extension path.replace(path.with_name('new_file').with_suffix('.csv'))

File Manipulation in Python

In this final part, we will explore file manipulation in Python using the tell() and seek() methods.

Use tell() to Get the Current Position

The tell() method can be used to get the current position of the file handle in the file.

It helps to determine from where data will be read or written in the file in terms of bytes from the beginning of the file.

You can think of the file handle as a cursor that defines where the data is read or written in the file. This method takes no parameter and returns an integer.

# Open a file in read mode with open("file.txt", "r") as file: # print position of handle print(file.tell()) # prints 0

You can find more information in the Python documentation.

Use seek() to Change Stream Positions

The seek() method is used to change the stream position. A stream is a sequence of data elements made available over time, and the stream position refers to the position of the pointer in the file.

The seek() method is useful if you need to read or write from a specific portion of the file. The syntax is:

  • fp is the file pointer.
  • offset is the number of positions you want to move. It can be a positive (going forwards) or negative (going backwards) number.
  • whence defines your point of reference. It can be:
    • 0: The beginning of the file.
    • 1: The current position in the file.
    • 2: The end of the file.

    If you omit the whence parameter, the default value is 0.

    When we open the file, the position is the beginning of the file. As we work with it, the position advances.

    The seek() function is useful when we need to walk along an open file. Let’s run a quick example:

    # Open a file with open("file.txt", "r") as file: file.seek(4) print(file.readline())

    You can find more information in the Python documentation.

    Learn More About Working with Files in Python

    We covered a lot of ground in this article. You’re getting some solid knowledge about file manipulation with Python.

    Now you know how to write to a file in Python and how to write data to a file in Python. We also briefly explored the tell() and seek() methods to manipulate a file.

    Don’t forget to check our course on Working with Files and Directories in Python to deepen and solidify your Python knowledge!

    Источник

    Python append to a file

    While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. The definition of these access modes is as follows:

    • Append Only (‘a’): Open the file for writing.
    • Append and Read (‘a+’): Open the file for reading and writing.

    When the file is opened in append mode in Python, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.

    Example 1: Python program to illustrate Append vs write mode.

    Python3

    Output of Readlines after appending This is Delhi This is Paris This is LondonToday Output of Readlines after writing Tomorrow

    Example 2: Append data from a new line

    In the above example of file handling, it can be seen that the data is not appended from the new line. This can be done by writing the newline ‘\n’ character to the file.

    Python3

    Output of Readlines after appending This is Delhi This is Paris This is London TodayTomorrow

    Note: ‘\n’ is treated as a special character of two bytes.

    Example 3: Using With statement in Python

    with statement is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources.

    Python3

    Hello This is Delhi This is Paris This is London Today

    Note: To know more about with statement click here.

    Using the shutil module:

    This approach uses the shutil.copyfileobj() method to append the contents of another file (source_file) to ‘file.txt’. This can be useful if you want to append the contents of one file to another without having to read the contents into memory first.

    Approach:
    The code uses the shutil.copyfileobj() function to copy the contents of the source_file object to a new file called file.txt. The with statement is used to open and automatically close the file, using the file object f.

    Time Complexity:
    The time complexity of shutil.copyfileobj() function is proportional to the size of the file being copied, as it needs to read and write every byte of the file. Therefore, the time complexity of the code is O(n), where n is the size of the source_file.

    Space Complexity:
    The space complexity of the code is O(1), as it does not allocate any additional memory beyond what is required for the file objects source_file and f. The shutil.copyfileobj() function copies the file contents in chunks, so it does not need to load the entire file into memory at once.

    Overall, the code has a linear time complexity and constant space complexity, where the time complexity is proportional to the size of the file being copied.

    Источник

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