Python full stack Road series of file operations

Source: Internet
Author: User
Python can view, create and other functions of the file, you can add, modify, delete the contents of the file, and the function used in python3.5.x to open, at the same time support python2.7.x fileAnd open, but removed from the 3.5.x series fileFunction.

How to open python files

File handle = open (' File path ', ' open mode ')

Ps: The file handle is equivalent to the variable name, and the file path can be written as an absolute path or as a relative path.

Python mode for opening files

The basic pattern

Precautions
Mode Description
R Read-only mode File must exist
W Write-only mode File does not exist, file is created, file contents are emptied
X Write-only mode The file is unreadable, the file does not exist, it is created, and there is an error
A Append mode File does not exist create file, file exists then add content at end of file

With + the pattern

Mode Description
r+ Write
w+ Write read
x+ Write read
A + Write read

With b the pattern

Mode Description
Rb Binary read mode
Wb Binary write mode
Xb Binary Write-only mode
Ab Binary Append mode

tip: when opened in B, the content read is byte type, and the byte type is also required for writing

Pattern with belt + b

Mode Description
rb+ Binary read-write mode
wb+ Binary read-write mode
xb+ Binary Write-only mode
ab+ Binary read-write mode

Python file read mode

Mode Description
Read ([size]) Reads the entire contents of the file, if size is set, then long reads the size byte
ReadLine ([size]) A row of reads
ReadLines () Read every line of content as an element in the list

The name of the test is the hello.tx" file content:

Hello WORD!123ABC456ABC789ABC

Read

Code:

# Open file in a read-only manner HELLO.TXTF = opened ("Hello.txt", "R") # reads the contents of the file to the variable cc = F.read () # Close File F.close () # Output C value print (c)

Output Result:

C:\Python35\python.exe F:/python_code/sublime/day06/file.pyhello WORD!123ABC456ABC789ABC

ReadLine

Code:

# opening file in read-only mode HELLO.TXTF = open ("Hello.txt", "R") # reads the first line C1 = F.readline () # reads the second line C2 = F.readline () # reads the third line C3 = F.readline () # Close the text Piece f.close () # output read file first line content print (c1) # output read file second line content print (C2) # output read file third line content print (C3)

Output Result:

C:\Python35\python.exe F:/python_code/sublime/day06/file.pyhello WORD!123ABC

ReadLines

# Open the file in a read-only way = HELLO.TXTF = Open ("Hello.txt", "R") # assigns all contents of the file to CC = F.readlines () # View data type print (type (c)) # Close File F.close () # Traversing output file contents for N in C:    print (n)

Results

C:\Python35\python.exe f:/python_code/sublime/day06/file.py# output data type <class ' list ' >hello word! 123abc456abc789abc

How Python files are written

Method Description
Write (str) Writing a string to a file
Writelines (sequence or strings) Write multiple lines to a file, parameters can be an iterative object, lists, tuples, etc.

Write

Code:

# Open file in read-only mode write.txt, no then create, have overwrite content file = open ("Write.txt", "W") # Write String Test writefile.write ("Test write") in the contents of the document # Close File File.close ()

write.txtThe contents of the file are:

Test Write

Writelines

Code:

# Open a nonexistent file in read-only mode WR_LINES.TXTF = open ("Wr_lines.txt", "W", encoding= "Utf-8") # Write a list f.writelines (["11", "22", "33"]) # Close File F.close ()

wr_lines.txtFile contents:

112233

Methods provided by the Python file operation

Close (self):

Close files that are already open

F.close ()

Fileno (self):

File descriptor

f = open ("Hello.txt", "r") ret = F.fileno () f.close () print (ret)

Execution Result:

3

Flush (self):

Flush the contents of the buffer to the hard disk

F.flush ()

Isatty (self):

Determine if the file is a TTY device and return if it is a TTY device, True otherwiseFalse

f = open ("Hello.txt", "r") ret = F.isatty () f.close () print (ret)

return Result:

C:\Python35\python.exe F:/python_code/sublime/day06/file.pyfalse

Readable (self):

is readable if it is readable and returns True otherwiseFalse

f = open ("Hello.txt", "r") ret = f.readable () f.close () print (ret)

return Result:

C:\Python35\python.exe F:/python_code/sublime/day06/file.pytrue

ReadLine (self, limit=-1):

Read only one row of data at a time

f = open ("Hello.txt", "R") print (F.readline ()) print (F.readline ()) F.close ()

return Result:

C:\Python35\python.exe F:/python_code/sublime/day06/file.pyhello word!123

ReadLines (self, hint=-1):

Treat each line as an element in the list

f = open ("Hello.txt", "R") print (F.readlines ()) F.close ()

return Result:

C:\Python35\python.exe f:/python_code/sublime/day06/file.py[' Hello word!\n ', ' 123\n ', ' abc\n ', ' 456\n ', ' abc\n ', ' 789 \ n ', ' abc ']
    • Tell (self):

Get pointer position

f = open ("Hello.txt", "R") print (F.tell ()) F.close ()

return Result:

C:\Python35\python.exe f:/python_code/sublime/day06/file.py0

Seek (self, offset, whence=io. Seek_set):

Specify pointer position in file

f = open ("Hello.txt", "R") print (F.tell ()) F.seek (3) print (F.tell ()) F.close ()

Execution results

C:\Python35\python.exe f:/python_code/sublime/day06/file.py03

Seekable (self):

Whether the pointer can be manipulated

f = open ("Hello.txt", "R") print (F.seekable ()) F.close ()

Execution results

C:\Python35\python.exe F:/python_code/sublime/day06/file.pytrue

Writable (self):

Whether it can be written

f = open ("Hello.txt", "R") print (F.writable ()) F.close ()

Execution results

C:\Python35\python.exe F:/python_code/sublime/day06/file.pyfalse

Writelines (self, lines):

A sequence of strings written to a file, which can be produced for any iteration of an object string, usually one 字符串列表 .

f = open ("Wr_lines.txt", "W") F.writelines (["One", "Max", "" "]) F.close ()

Execution results

112233

Read (self, n=none):

Reads the specified byte data, followed by the default read all without parameters

f = open ("Wr_lines.txt", "R") print (F.read (3)) F.seek (0) print (F.read ()) F.close ()

Execution results

C:\Python35\python.exe f:/python_code/sublime/day06/file.py112112233

Write (self, s):

Write content to the file

f = open ("Wr_lines.txt", "W") F.write ("Abcabcabc") F.close ()

File contents

Abcabcabc

Open multiple files at the same time

To avoid forgetting to close a file after opening it, you can manage the context by:

With open (' Log ', ' R ') as F: code block

This way, when the with code block finishes executing, the internal automatically shuts down and frees the file resource.

In Python 2.7 and later, with also supports the management of multiple file contexts simultaneously, namely:

With open (' Log1 ') as Obj1, open (' log2 ') as Obj2:    Pass
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.