Python File Operations Summary

Source: Internet
Author: User
Tags readable

One, the common method of file operation:

1. Read (): Read the rest of the entire file from the cursor position, note that it starts at the cursor position and does not necessarily read the entire file.

#first time read:F=open ('Test.txt','R')Print(F.read ()) F.close ()#since the fear of amorous loss of the Vatican, into the mountains and fear of the wrong. The world of the law, the Buddha is not negative.Cang Gyatso#Second ReadF=open ('Test.txt','R') F.readline ()Print(F.read ())#Cang GyatsoF.close ()

2. The difference between ReadLine and ReadLines:

#ReadLine () reads only one line and then moves the cursor to the next lineF=open ('Test.txt','R')Print(F.readline ())#since the fear of amorous loss of the Vatican, into the mountains and fear of the wrong. The world of the law, the Buddha is not negative.Print(F.readline ())#Cang Gyatsof.close ()#Readllines () reads the entire file and then saves each business as an element into a list. Note that each element is followed by a break symbolF=open ('Test.txt','R')Print(F.readlines ())#[' Since the fear of sentimental damage to the Vatican, into the mountains and fear of the wrong. The world of the law, the Tathagata is not negative. \ n ', ' Cang Gyatso \ n ']f.close ()#Finally, a point: ReadLines is to write all the files in memory once, if the file is small, once the file is big, it will be fatal. Large files can be read and written using the following method:With open ('Test.txt','R') as F: forLineinchF:Print(Line.strip ())#the benefit of this reading and writing is that one line reads, and it is released after reading, completely free of memory. 

3, Write,writelines

F.write ('1111\n222\n')#Write to text mode, you need to write line breakF.write ('1111\n222\n'. Encode ('Utf-8'))#Write line break for B modeF.writelines (['333\n','444\n'])#file ModeF.writelines ([Bytes ('333\n', encoding='Utf-8'),'444\n'. Encode ('Utf-8')])#b Mode

4. Other methods:

# whether the file is readable # whether the file is readable # whether the file is closed # if the file open mode is B, the attribute is not # immediately swipe the contents of the file from the memory to the hard drive f.name   # file name

Second, the movement of the file cursor:

1, read (n) when the file is opened in a text mode, the delegate reads n characters , the file opens in the mode B mode, the delegate reads n bytes

#1. Read in text modeWith open ('Test.txt','R') as F:Print(F.read (4))#self-fearing amorous#2. Read in byte mode:With open ('Test.txt','RB') as F:Print(F.read (4). Decode ('GBK'))#Self-Fear#Direct output: Print (F.read ()) output is B ' \xd7\xd4\xbf\xd6 '

2. Tell () Gets the position of the current file pointer, no parameters. Computes the return in bytes

With open ('test.txt','r') as F:    Print # self-fearing amorous    Print (F.tell ())   # 8

3, Seek () function: Used to move the file read and write pointer to the specified location.

#the prototype of the function is: File.seek (offset,whence=0)Offset refers to the offsets, whence have three values, 0,1,2. 0 means move to the beginning of the file, 1, referring to the current position, 2 refers to the end of the file. The default value of 0 is used by default. #Note: You must open the file in byte mode B using the parameter! With Open ('Test.txt','R') as F:Print(F.read (4))#self-fearing amorous    Print(F.tell ())#8F.seek (0,0)#return to start    Print(F.read (4))#self-fearing amorousWith Open ('Test.txt','RB') as F:Print(F.read (4). Decode ('GBK'))#Self-FearF.seek ( -4,1)    Print(F.read (4). Decode ('GBK'))#Self-FearWith Open ('Test.txt','RB') as F:f.seek (-4,2)    Print(F.read (4). Decode ('GBK'))#Gyatso

Ii. Modification of documents:

In fact, we usually say to fix a file somewhere, actually is not directly modify the file, but overwrite. File data is stored on the hard disk, so there is only coverage, there is no modification so, we usually see the modified files, are simulated results, we can use the following code to simulate the process.

ImportOswith Open ('Test.txt','R') as F, open ('Test_1.txt','W') as F1: forLineinchF:line=line.replace ('since the fear of amorous loss of the Vatican, into the mountains and fear of the wrong. The world of the law, the Buddha is not negative.',                          'do not fear the amorous loss of the Vatican, lest into the mountains mistakenly. The world of the law, better than the Buddha to bear the Qing.') Line=line.replace ('Cang Gyatso','yo, write a bug?? ') F1.write (line) Os.remove ('Test.txt') Os.rename ('Test_1.txt','Test.txt')

Python File Operations Summary

Related Article

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.