[Python 1-17] Python hand in hand tutorial (Part 1) — file reading and writing and I / O operation

Time:2021-1-26

Author: Vlad
Source Vlad (official account: fulade_ me)

Reading data from a file

Text files can store a large amount of data. Whenever you need to analyze or modify the information stored in the file, it is very useful to read the file, especially for data analysis applications. For example, you can write a program that reads the contents of a text file, reformats the data and writes it to the file so that the browser can display the contents.
To use the information in a text file, you first need to read the information into memory. To do this, you can read the entire contents of the file at one time, or you can read it one line at a time step by step.

Read entire file

To read a file, you need a file that contains several lines of text. Let’s first create a file, which contains the pI value accurate to 30 decimal places, and wrap every 10 decimal places

3.1415926535 
8979323846 
2643383279

We save it aspi_digits.txtfile

with open('pi_digits.txt') as file_object: 
    contents = file_object.read() 
    print(contents)

Let’s look at the function firstopen(). To use a file in any way, even if you just print its contents, you have to open the file before you can access it. functionopen()Take a parameter: the name of the file to open. Python finds the specified file in the directory where the currently executing file is located. In this example, suppose we save the file asfile_reader.pySo Pythonfile_reader.pyIn the same directorypi_digits.txt. functionopen()Returns an object representing the file. ad locum,open('pi_digits.txt')Returns a representation filepi_digits.txtPython stores this object in the variable we will use later.
keywordwithClose the file when you no longer need to access it. In this program, notice that we call theopen(), but not calledclose()You can also callopen()andclose()To open and close the file, but when doing so, if there is a bug in the program, it will lead toclose()Statement is not executed and the file will not be closed. This may seem trivial, but failing to close the file properly may result in data loss or corruption. If called prematurely in a programclose(), you will find that the file is closed when you need to use it, which will lead to more errors. It’s not easy to determine the right time to close a file in any case, but by using the structure shown above, you can let Python determine that you just open the file and use it when you need it, and python will automatically close it at the right time.
By printingcontentsTo display all the contents of this text file:

3.1415926535 
8979323846 
2643383279

File path

When you will be similarpi_digits.txtSuch a simple file name is passed to the functionopen()Python looks for the file in the same directory as the currently executing file.
Depending on how you organize your files, sometimes you may want to open files that are not in the directory of the program file. For example, you may have stored program files in a folderpython_workIn the folderpython_workAmong them, there is one namedtext_filesFolder for storing text files for program file operations. Although the foldertext_filesInclude in folderpython_workMedium, but only toopen()It’s also not feasible to pass the name of the file located in the folder, because Python is only in the folderpython_workInstead of looking in its subfolderstext_filesFind in. To make Python open a file that is not in the same directory as the program file, you need to provide a file path, which allows Python to find a specific location in the system.
Due to foldertext_filesIn folderpython_workSo you can use the relative file path to open the files in that folder. Relative file path allows Python to find the specified location relative to the directory of the currently running program. In Linux and OS X, you can write code like this:

with open('text_files/filename.txt') as file_object:

This line of code takes Python to the folderpython_workFolder undertext_filesTo find the specified. TXT file in. In Windows system, use backslash in file path\Not slashes/:

with open('text_files\filename.txt') as file_object:

You can also tell Python the exact location of the file on your computer, so you don’t have to care where the currently running program is stored. This is called the absolute file path. When the relative path doesn’t work, the absolute path can be used. For example, iftext_filesIt’s not in the folderpython_workIn the folderother_filesIn the middle, then to the middleopen()Delivery path'text_files/ filename.txt'It doesn’t work because Python only works in folderspython_workFind the location in. To clearly indicate where you want Python to look, you need to provide a complete path.
The absolute path is usually longer than the relative path, so it is stored in a variable and passed to theopen()It will help. In Linux and OS X, the absolute path is similar to the following:

file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:

In windows, they are similar to the following:

file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:

By using absolute paths, you can read files anywhere on the system. At present, the simplest way is to either store the data file in the directory where the program file is located, or store it in a folder under the directory where the program file is located (such astext_files)In the middle.

Read line by line

When reading a file, you often need to check each line: you may want to look for specific information in the file, or you may want to modify the text in the file in some way. For example, you might want to traverse a file that contains weather data and use the words included in the weather descriptionsunnyYes. In news reports, you may look for the include tag<headline>And set it in a specific format.
To check a file one line at a time, use the for loop on the file object:

filename = 'pi_digits.txt'
with open(filename) as file_object: 
    for line in file_object:
    print(line)

The name of the file we are going to read is stored in the variablefilenameThis is a common practice when using files. Due to variablefilenameIt doesn’t represent the actual file – it’s just a string that lets Python know where to look for the file, so it’s easy to put ‘Pi’_ digits.txt ‘replace with the name of another file you want to use.

callopen()After that, an object representing the file and its contents is stored in a variablefile_objectIn the middle. Keywords are also used herewith, leaving Python responsible for opening and closing files properly. In order to view the contents of the file, we iterate through each line of the file by executing a loop on the file object. When we print each line, we find that there are more blank lines:

3.1415926535 

8979323846

2643383279

Why do these blank lines appear? Because in this file, there is an invisible newline at the end of each lineprintThe statement also adds a line break, so there are two line breaks at the end of each line: one from a file and one from a fileprintsentence.

Create a list containing the contents of each line of the file

When using the keyword with,open()The returned file object is only in thewithAvailable within the code block. If you want towithThe contents of the file can be accessed outside the code blockwithIn the code block, the lines of the file are stored in a list, and thewithUse the list outside the code block: you can deal with parts of the file immediately or later in the program.
The following example is inwithAdd the file to the code blockpi_digits.txtThe rows of are stored in a list, and then in thewithPrint them out of the code block:

filename = 'pi_digits.txt'
with open(filename) as file_object:
    lines = file_object.readlines() 
for line in lines:
    print(line.rstrip())

Let’s use the method firstreadlines()Each line is read from the file and stored in a list, which is then stored in a variablelinesIn; inwithWe can still use this variable outside the code block. We use a simple for loop to printlinesEach line in the book. Due to the listlinesEach element of corresponds to a line in the file, so the output is exactly the same as the content of the file.

Use the contents of the document

After reading the file into memory, you can use the data in any way. The following uses the value of PI in a simple way. First, we will create a string that contains all the numbers stored in the file without any spaces:


filename = 'pi_digits.txt'
with open(filename) as file_object: 
    lines = file_object.readlines()
pi_string = '' 
for line in lines:
    pi_string += line.rstrip()
print(pi_string) 
print(len(pi_string))

As in the previous example, we first open the file and store all the lines in it in a list. We create a variable——pi_stringTo store the value of PI. Next, we use a loop to add all the rowspi_string, and remove the newline at the end of each line. Next, we print the string and its length:

3.1415926535 8979323846 2643383279
36

In variablepi_stringThe stored string contains the original spaces on the left side of each line. To delete these spaces, you can use thestrip()instead ofrstrip():

filename = 'pi_30_digits.txt'
with open(filename) as file_object: 
    lines = file_object.readlines()
pi_string = ''
for line in lines:
    pi_string += line.strip()
print(pi_string) 
print(len(pi_string))

In this way, we get a string that contains the pI value to 30 decimal places. This string is 32 characters long, because it also contains the integer part 3 and the decimal point:

3.141592653589793238462643383279
36

write file

One of the easiest ways to save data is to write it to a file. By writing the output to a file, even if the terminal window containing the program output is closed, the output still exists: you can view the output after the program is finished, share the output file with others, and write a program to read the output into memory and process it.

Write empty file

To write text to a file, you need to provide another argument when calling open (), telling python that you want to write to the open file. To understand how it works, let’s store a simple message in a file instead of printing it to the screen

filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programming.")

In this example, theopen()Two arguments are provided when. The first argument is also the name of the file to be opened; the second argumentwTell python that we want to open the file in write mode. When you open a file, you can specify the read moder, write modew, additional modeaOr a mode that allows you to read and write filesr+. If you omit the mode argument, python will open the file in the default read-only mode.

If the file you want to write does not exist, the functionopen()It will be created automatically. However, to writewBe careful when opening a file in mode, because if the specified file already exists, python will empty it before returning the file object.
The way we use file objectswrite()Writes a string to a file. This program has no terminal output, but if you open the fileprogramming.txt, you will see the following line:

I love programming.

This file is no different from other files on your computer. You can open it, enter new text in it, copy its content, paste its content into it, and so on.

Write multiple lines

functionwrite()You don’t add a newline at the end of the text you write, so if you don’t specify a newline when you write multiple lines,
The file may not look what you want it to look like:

filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programming.") 
    file_object.write("I love creating new games.")

If you open it programming.txt , will find two lines of content squeezed together:

I love programming.I love creating new games.

For each string to occupy a single line, you need towrite()Statement contains line breaks:

filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programming.\n") 
    file_object.write("I love creating new games\n")

Now the output appears in different lines:

I love programming.
I love creating new games.

Add write file

If you want to add content to the file instead of covering the original content, you can open the file in attach mode. You areAdditional modeWhen you open a file, python does not empty the file before returning the file object, and the lines you write to the file are added to the end of the file. If the specified file does not exist, python will create an empty file for you.

filename = 'programming.txt'
with open(filename, 'a') as file_object:
    file_object.write("I also love finding meaning in large datasets.\n")
    file_object.write("I love creating apps that can run in a browser.\n")

We specified arguments when we opened the fileaTo attach the content to the end of the file instead of overriding the original content of the file. Then we write two more lines, which are added to the fileprogramming.txtend:

I love programming.
I love creating new games.
I also love finding meaning in large datasets.
I love creating apps that can run in a browser.

The end result is that the original contents of the file are still there, followed by the contents we just added. nineteen

Homework
17-1 create a new file in the text editor and write a few sentences to summarize what you have learned
Here’s what you learned about python. Name this file learning_ python.txt And store it in the directory of the program you wrote to complete the exercises in this chapter. Write a program, read the entire file, and print.
17-2 visitor: write a program to prompt the user to enter his name; after the user responds, write his name to the file guest.txt In the middle.

If you want to check the answers to your homework, you can goMy githu warehouseIn folder17-1_17-2lower


[Python 1-17] Python hand in hand tutorial (Part 1) -- file reading and writing and I / O operation