Python file operations

Source: Internet
Author: User

File operation:
Os.mknod ("test.txt") Create an empty file
fp = open ("test.txt", w) open a file directly and create a file if the file does not exist

About Open Mode:

W opens in write mode,
a opens in Append mode (starting with EOF and creating a new file if Necessary)
r+ Open in Read-write mode
w+ Open in read/write mode (see w)
A + opens in Read/write mode (see a)
RB opens in binary read mode
WB opens in binary write mode (see w)
AB opens in binary append mode (see a)
rb+ opens in binary read/write mode (see r+)
wb+ opens in binary read/write mode (see w+)
ab+ opens in binary read/write mode (see a +)

Fp.read ([size]) #size为读取的长度, in bytes

fp.readline ([size]) #读一行, If size is defined, it is possible to return only part of a row

fp.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns the List. In fact, its internal is through the loop call ReadLine () to Achieve. If you provide a size parameter, size is the total length of the read content, which means that it may be read only to a portion of the File.

fp.write (str) #把str写到文件中, write () does not add a newline character after Str

fp.writelines (seq) #把seq的内容全部写到文件中 (multi-line write-once). This function simply writes faithfully and does not add anything behind each LINE.

fp.close () #关闭文件.  Python will automatically close files after a file is not used, but this feature is not guaranteed and it is best to develop a habit of shutting them down. If a file is closed and then manipulated, it generates VALUEERROR

Fp.flush () #把缓冲区的内容写入硬盘

Fp.fileno () #返回一个长整型的 "file label"

fp.isatty () #文件是否是一个终端设备文件 (on Unix Systems)

Fp.tell () #返回文件操作标记的当前位置, starting with the origin of the file

fp.next () #返回下一行 and shifts the file action marker to the next Line. When a file is used for a statement such as for ... in file, it is called the next () function to implement the Traversal.

Fp.seek (offset[,whence]) #将文件打操作标记移到offset的位置. This offset is generally calculated relative to the beginning of the file and is generally a positive number. however, if the whence parameter is provided, whence can be calculated from scratch for 0, and 1 for the current position as its origin. 2 means that the end of the file is calculated as the Origin. Note that if the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is Made.

fp.truncate ([size]) #把文件裁成规定的大小, The default is the location that is cropped to the current file action Tag. If the size of the file is larger, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add.


Example 1:

Log file contents

Abcdefghijklmn
f = Open (' log ', ' r ') print f.read () f.close ()

Script Execution Results:

~/pycharmprojects/project1 $ python file_demo.pyabcdefghijklmn

You can see that the Read () method defaults to reading the file from the Beginning.


Example 2: reading a file starting from the specified pointer position

f = Open (' log ', ' r ') f.seek (4) print f.read () f.close ()

Script Execution Results:

~/pycharmprojects/project1 $ python file_demo.py efghijklmn


Example 3:truncate () mode

The Truncate () method is used to intercept the file, which is the contents of the file 0 pointer position to the current pointer position, note that when using TRUNCATE mode, the file requires read and write Permissions. That is, the file mode is r+

f = Open (' log ', ' r+ ') f.seek (4)//specify The position of the file pointer to 4f.truncate () f.close ()

File Execution Results

~/pycharmprojects/project1 $ cat LOGABCD

You can see that the contents of the intercepted file are from the 0 pointer to the position of the 4th pointer



With open ()

With open () can also be used to manipulate the file, and it is better than open (), because it can automatically close the file


Usage example 1: read file contents with open ()

With open (' log ', ' r ') as F:for line in F:print line

Script Execution Results

~/pycharmprojects/project1 $ python file_demo.pyabcdefghcdf


Example 2: Modifying the contents of a file

F=open (' log ', ' r ') line=f.readlines () for I in range (len): if ' a ' in Line[i]: line[i]=line[i].replace (' a ', ' A ') f=open (' log ', ' w+ ') f.writelines (line) f.close ()

Script Execution Results

~/pycharmprojects/project1 $ cat Logaaaabbbaaaacccaaaasfasfasasdfasdf

The above example is written in a function like this

Modify (filename,oldstr,newstr):: f= (filename,) line=f.readlines () I (line): oldstr L Ine[i]: line[i]=line[i].replace (oldstr,newstr) f= (filename,) f.writelines (line) F.clos E (), e:e: f.close () Modify (,,)


Example 3, modifying file contents with open ()

List1=[]with Open (' log ', ' r ') as Obj:for line in obj:new_line = Line.replace (' a ', ' a ') list1.append (new_l Ine) Print List1with Open (' log ', ' w+ ') as Obj1:obj1.writelines (list1)

Idea: read the contents of each line of the file first, replace it (replace it with replacement, leave it as it is), then save the replaced row contents to the list, then open the file in w+ mode and write the contents of the list to the file using the Writelines () method.

The w+ method flushes the contents of the file before Writing.


Example 4, Modifying the contents of a file and backing it up to a new file

With open (' log ', ' r ') as obj1, open (' log_new ', ' W ') as Obj2:for line in obj1:new_line = line.replace (' 1111 ', ' 6 ') Obj2.write (new_line)


Example 5, modifying a file with regular expressions

ref= (,) lines=f.read () f1= (,) f1.write (re.sub (,, lines)) f1.close ()

The code above is shorthand for This.

ref = (,) Str=f.read () (,). write (re.sub (,, Str))








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.