Python open () file handling using introduction _python

Source: Internet
Author: User
Tags file handling readline

1. Open () syntax

Open (file[, mode[, buffering[, encoding[, errors[, newline[, Closefd=true]]] []]
The Open function has many parameters, often file,mode and encoding
file location, which requires quotes
mode File open mode, see the following 3
buffering The desirable values are 0,1,>1 three, 0 for buffer shutdown (only for binary mode), 1 for line Buffer (for text mode only), >1 represents the initialized buffer size; the
encoding represents the encoding of the returned data, generally using UTF8 or GBK;
Errors The value is generally strict,ignore, when the strict, when the character encoding problems, will be an error, when the ignore, coding problems, the program will ignore, continue to execute the following procedure.
NewLine can take a value that has none, \ n, \ r, ", ' \ r \ n ', used to differentiate line breaks, but this argument is valid only for text patterns;
closefd values, is related to the incoming file parameter, by default, True, the incoming file parameter is the file name of the filename, and when the value is false, file can only be a filename descriptor, a file descriptor, a non-negative integer, and a file is opened in the Unix kernel system. A file descriptor is returned.

2. The difference between file () and open () in Python
Both have the ability to open files, manipulate files, and have similar usage and parameters, but there is a fundamental difference between the two types of file opening, fileclass , and file () to open files , which is equivalent to constructing the file class, and using the open () To open the file, use Python's built-in function to manipulate it, it is recommended to use open

3. Basic values of parameter mode

Character meaning
' R ' open for reading (default)
' W ' /span> Open for writing, truncating the file,
' a ' Open for writing, appending to the ' end of ' the ' file if it exists
binary mode
' t ' text mode (default)
' + ' open a disk file for updating (reading and writing)
' U ' Universal newline mode (for backwards compatibility; Sho Uld not is used in new code)

R, W, A is the basic mode of open file, corresponding to read-only, write-only, append mode;
B, T, +, u these four characters, with the above file open mode combination use, binary mode, text mode, read and write mode, general line break, according to the actual situation combined use,

A common mode fetch combination

R or RT default mode, text mode read
RB   binary
 
w or wt text mode write, before opening file storage is emptied
WB  binary Write, file storage is also emptied of
 
a  append mode, can only write at the end of the file A
+ can read and write mode, writing can only write at the end of the file
 
w+ can read and write, and A + is the difference is to empty the contents of the file
r+ can read and write, and A + is the difference can be written to a file anywhere

4. Test
Test file Test.txt, which reads as follows:

Hello,python
Www.jb51.net This is
a test file

Use a small piece of code to test write files visually display their differences

Test = ["test1\n", "test2\n", "test3\n"]
f = open ("Test.txt", "A +")
try:
 #f. Seek (0) for
 L in test:
  f.write (L)
finally:
 f.close ()

the difference between A +, w+ and r+ patterns (after test restore Test.txt)
A + mode

# cat Test.txt
Hello, Python
www.jb51.net This is
a test file
test1
test2
test3

w+ mode

# cat Test.txt
test1
test2
test3

r+ mode
Before writing the file, we add a f.seek (0) to the above code to locate the write file write location (at the beginning of the file) and directly overwrite the number of characters (note \ n is also a character)

# cat Test.txt
test1
test2
test3
inuxeye.com This is
a test file

Note: When you open a file in r+ mode, this file must exist, or it will be an error, and the ' R ' mode is the same
Other tests

>>> f = open (' test.txt ')
>>> f.read () #读取整个文件, string display
' Hello,python\nwww.jb51.net\nthis is A test file\n '
>>> f.read () #指针在文件末尾, no longer read the content
'
>>> f = open (' test.txt ')
>>> f.readline () #一次读一行, the pointer is at the end of the line
' hello,python\n '
>> > F.tell () #改行的字符长度
>>> f.readline ()
' www.jb51.net\n '
>>> F.tell ()
30
>>> f.readline ()
' This is a test file\n '
>>> F.tell ()
>>> F.readline ()
'
>>> F.tell () #指针停在最后一行
50
>>> f = open (' test.txt ')
>>> f.readlines () #读取整个文件 to list display
[' hello,python\n ', ' Www.jb51.net\n ', ' This is a test file\n ']
>>> F.tell () #指针在最后一行
50
>>> f = open (' Test.txt ', ' W ') #覆盖创建新文件
>>> f.write (' hello,python! ') #如果写入内容小于1024, there will be memory, otherwise you need to refresh
>>> F.flush () #写入到硬盘
>>> f.close () #关闭文件会自动刷新
>>> f.write (' Hello, Linuxeye ') #关闭后, write failed, hint file has been closed
Traceback (most recent call last):
 file "<stdin>", line 1, in <module >

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.