Python file operations

Source: Internet
Author: User
Tags for in range

Python file related operations open file

Open the file, using the open method, will return the File's handle, as Follows:

f = open ('test_file.txt','r', encoding='utf-8  ')

In the above code, the open () method opens a file and other related operations, The open () method where the first parameter is the file path of the file to open, the second parameter is the permission to open the file to execute, and the third parameter is the file character encoding.

The content returned by the open () method is called a file Handle. We can print back the file handle to look at:

f = open ('test_file.txt','r', encoding='utf-8  ')print

The results of the implementation are as Follows:

 <_io.TextIOWrapper name=‘test_file.txt‘ mode=‘r‘ encoding=‘utf-8‘>

In this case, the file handle F contains information about the file being opened, and we can get information about the file through some properties and METHODS.

File name

Get opened file Name: F.name

f = open ('test_file.txt','r', encoding='utf-8  ')print#  test_file.txt

File pointers

When using Python to read the file, you need to refer to the file pointer to read, and below we can look at the relevant operation of the file Pointer.

Get File pointer location

Get the file pointer position you can use the Tell () method to get the file pointer position

# Open file f = open ('test_file.txt','r', encoding='  utf-8')#  Gets the file pointer position print#  The value returned is where the file pointer is located

It is important to note that the file pointer is not constant, and the position of the pointer changes as the file is Read.

Adjust file pointer position

Because the pointer to the file changes as the file is read, you need to adjust the file pointer if you need to re-read the read location, and in python, if you want to adjust the file pointer, you can use the Seek () method

The code is as Follows:

# Open file f = open ('test_file.txt','r', encoding='  utf-8'#  Adjust the file pointer to the initial 0 position

It is important to note that the Seek () method is written in parentheses where the pointer is to be adjusted, and if this parameter is not set, the error is Performed.
typically, we set the parameter to 0.

Determine if the file pointer can be moved

At some point in python, we need to determine whether pointers can be moved, and implementing such requirements requires the seekable () method. Returns true if it can be moved, false if it cannot be moved

# seekable () method to determine whether the current file pointer can be moved Print # True

Determine the character encoding of a file

The encoding attribute can be used to determine the character encoding of a file.

Print (f.encoding)

View the number of files in memory

To view the number of files in memory, you can use the Fileno () method

Print (f.fileno ())

To determine if a file is readable and writable

In Python file operations, you need to give different permissions to the file handle, and the file permissions we commonly use are as Follows:

The mode of opening the file is:

    • r, read-only Mode (default).
    • w, write-only Mode. "unreadable; not exist; create; Delete content;"
    • a, Append Mode. "readable; not exist" create; "only append content;"

"+" means you can read and write a file at the same time

    • r+, can read and write Files. "readable; writable; can be added"
    • w+, Write and read
    • A +, with a

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading

    • RU
    • R+u

"b" means processing binary files (E.G. ftp send upload ISO image file, Linux can be ignored, Windows process binary file should be Labeled)

    • Rb
    • Wb
    • Ab

The settings of the file permissions can be set differently depending on the requirements, but usually we use the most to be readable and writable when judging what permissions the file Has.

Determine if the file is readable, use the readable () method, determine if the file is writable, and use the writeable () method.

# Open file f = open ('test_file.txt','r', encoding='  utf-8')# to determine the file readable writable permission print(f.readable ( ))print(f.writable ())

Determine if the file is closed

File is open, you need to close the file when it is not needed, thereby saving performance resources, then close the file in Python using the close () method, and determine whether the file is closed, using the closed () method.

f = open ('test_file.txt','r', encoding='utf-8  ')print(f.closed)

Reading a file reads a line from a file

In python, to read a single line of content in a file, you can use the ReadLine () method, as Follows:

# Open file f = open ('test_file.txt','r', encoding='  utf-8')#  reads a line from the file print

The ReadLine () method allows you to read a line of content in a file and, of course, you can continue to use the ReadLine () method if you want to continue reading the next Line.

Print (f.readline ())

It's important to note, then, that each time a row is read, the pointer changes in the file, and we can use the tell () method to see the changes in the file Pointer.

Print#  after reading a line, use the Tell () method to view a pointer to the contents of the File.  print(f.tell ())

of course, If you want to read and output more rows in the file, you can loop through the Way.

The contents of the file are as Follows:

白日依山尽,黄河入海流。欲穷千里目,更上一层楼。

Then the loop reads the output four Lines:

# Open file f = open ('test_file.txt','r', encoding='  utf-8')#  want to read output four lines  for in range (4 ):    Print

Results of the Output:

白日依山尽,黄河入海流。欲穷千里目,更上一层楼。

At this point, through the loop we have successfully all the files in the four lines of content output, but found that there is a line between each row of empty lines, because at the end of each line there is a \ n line-break, you can use the Rstrip () method to remove the line, the code is as Follows:

# You can change the above loop to the following notation  for  in range (4):    Print

Then the output style after the code change is as Follows:

白日依山尽,黄河入海流。欲穷千里目,更上一层楼。

The newline after each sentence has been successfully removed.

But then there is the question of how to read and output all the rows when the number of rows in the file is not clear.

Read all rows in a file

To read all the rows in a file, you can use the ReadLines () method.

The code is as Follows:

# Open file f = open ('test_file.txt','r', encoding='  utf-8')#  reads all the lines in the file print(f.readlines ())

The output reads as Follows:

[‘白日依山尽,\n‘, ‘黄河入海流。\n‘, ‘欲穷千里目,\n‘, ‘更上一层楼。‘]

Then we find that the content type of the output at this time is a List. And the last of each list element contains a newline \ N.

If we want to read all the contents of the returned output, we can use the following method:

# Open file f = open ('test_file.txt','r', encoding='  utf-8') for in (f.readlines ()):      Print(index.rstrip ())

The results of the output are as Follows:

白日依山尽,黄河入海流。欲穷千里目,更上一层楼。

So at this point, if we want to specifically output one of these lines, we can use the following notation:

# Open file f = open ('test_file.txt','r', encoding='  utf-8') for in enumerate (f.readlines ()):     if index = =2        :print(line.rstrip ()    )Else :         Continue

The result of the output is:

欲穷千里目,

The above code in the writing has been perfect to achieve the output file all the content of the requirements, but from the actual application point of view, the above is only suitable for the reading of the file is small, if the file is read large, then the above code will cause the program to wait Longer.

Recommended notation for all content in a read file

So in order to solve the above problem, we can change the reading of all the contents of the file as Follows:

# Open file f = open ('test_file.txt','r', encoding='  utf-8')#  reads all the contents  of the file for in F:     Print (line.rstrip ())

The resulting output is:
The day is done by the mountain,
The Yellow River is in the Ocean.
to the poor,
Better.
similarly, This approach now achieves the final effect of the above Example.

So what is the difference between these two methods?

The first method, read all the contents of the file is the ReadLines () method, first to all the contents of the file all the content read, and then to do other operations processing, and the second way is a line of read.

When we read a large file in the first way, it causes the wait time to be too long, and the second method does not have this Problem.

So if you want to implement a specific line in the output content, you can use a similar notation like this:

# Open file f = open ('test_file.txt','r', encoding='  utf-8')#  reads the second line in the file count = for inch F:     if count = = 1        :print(line    )+ = 1

Tip: reading the contents of a file can also be used in the following way

# Open file f = open ('test_file.txt','r', encoding='  utf-8')print(f.read ())

Results of the Output:
The day is done by the mountain,
The Yellow River is in the Ocean.
to the poor,
Better.

however, This is not recommended because the output is not conducive to Operation.

Write Operations for files

Having said the read operation of the file, we are speaking of the write operation of the File.

first, to write content to a file, you need to change the permissions in the open () method as Follows:

# Open File  --change the File's permissions to Wf = open ('test_write.txt','w' ) , encoding='utf-8')

The Test_write.txt file is now a blank text file

Writing to a file can take the write () method

# Open File  --change the File's permissions to Wf = open ('test_write.txt','w' ) , encoding='utf-8')#  writes the content to the file using the Write () method F.write ( ' Hello,yanyan ')

At this point, after executing the code, the contents of the Test_write.txt file are changed from blank to Hello,yanyan

But when it comes to writing, it's important to note that when the open () method returns a file handle with the permission of w, we write the content to the file in a Python file, for example:

# Open File  --change the File's permissions to Wf = open ('test_write.txt','w' ) , encoding='utf-8')#  writes the content to the file using the Write () method F.write ( ' Hello,yanyan ' ) f.write ('hello,good gril')

Then the contents of the Test_write.txt file are as Follows:

Hello,YanYanHello,Good Gril

But once another code opens the Test_write.txt with the open () method, and the file handle has a permission of w, the content written in this code overwrites the contents of the Test_write.txt file, which means that test_ The content before Write.txt disappears and is then written to the new Content.

If you want to append new content based on the original content of the file, you need to change the permission W to A.

# Open File  --change The File's permissions to af = open ('test_write.txt','a' , encoding='utf-8')#  writes the content to the file using the Write () method F.write ( ' Yanyan is good gril ')

Then there is no Overwrite.

Tip: It is important to note that when we set the permissions of the file handle to W or a, it is not able to read the file, and if you want to be able to read and write, it is recommended to set the file permissions to r+, read and write mode, which can be read and can be written, is currently using a higher frequency file permissions

Flush () Method

In python, when we write to a file, it looks like the write code writes one line, and the file adds a Line.
In fact, when the system executes, the content written in the code is stored in the buffer, and stored in a uniform amount when stored in a certain number. The function of flush is to manually refresh the storage

Python file operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.