Python file basic operations

Source: Internet
Author: User

Python file basic operations 1, File object properties
Properties Description
File.closed Returns true if the file has been closed, otherwise false.
File.mode Returns the access mode of the file being opened.
File.name Returns the name of the file.
File.newlines None when the row delimiter is not read, only one row delimiter is a string, and when the file has more than one type of line terminator, it is a list that contains all the currently encountered line Terminators
File.encoding How to encode the returned file
file = open(‘allen.txt‘, ‘w‘)print(file.name)print(file.mode)print(file.encoding)print(file.newlines)输出结果:allen.txtwUTF-8None
2, the opening of the file

File Open is through the built-in function open () and returns a file object,

file object = open(file_name [, access_mode][, buffering])
    • The File_name:file_name variable is a string value that contains the name of the file you want to access. For example: ' Hello.text '

    • Access_mode: Access the file's mode, read-only (R), write (W), append (a), etc. All the desirable values are shown in the full list below. This parameter is non-mandatory and the default file access mode is read-only (R).

    • Buffering: The value is 0, the row is not stored when the file is accessed. A value of 1, which registers the row when the file is accessed. A positive number greater than 1 indicates the buffer size for the specified storage area. A negative value indicates that the register buffer size is the system default.

A table wins 10 article:

Mode Description
R Open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
Rb Opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. Generally used for non-text files and so on.
r+ Open the file as read-write, the file's pointer at the beginning of the file
rb+ Opening a file in binary format can be used to read and write, and the file pointer is placed at the beginning. Generally used for non-text files and so on.
W Open the file as write-only, the pointer to the file at the beginning of the file, overwriting it if the file already exists. If the file does not exist, create a new file.
Wb Opens a file in binary format for write-only, a pointer to the file at the beginning of the file. Overwrite the file if it already exists. If the file does not exist, create a new file. Generally used for non-text files and so on.
w+ Open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
wb+ Opens a file in binary format for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. Generally used for non-text files and so on.
A Opens a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to.
Ab Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. r+
A + Open a file for read-write. If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write.
ab+ Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to read and write.

One graph wins 10 tables:

A
Mode R r+ W w+ a+
Read ?? ?? ? ?? ? ??
Write ? ?? ?? ?? ?? ??
Create ? ? ?? ?? ?? ??
Covered ? ? ?? ?? ? ?
The pointer is at the beginning ?? ?? ?? ?? ? ?
Pointer at the end ? ? ? ? ?? ??
3. File input

File input and output is relative to the screen, from reading the contents of the file to the screen called input, the contents of the screen is written to the file called output

3.1 Read (size):

Used to read the specified number of bytes from a file, size: The number of bytes read from the file. If size is not given or is negative read all
Allen.txt File Contents

line1line2line3
file = open(‘allen.txt‘, ‘r‘)cont1 = file.read(2)cont2 = file.read(10)cont3 = file.read(15)print(‘cont1=%s‘ % cont1)print(‘cont2=%s‘ % cont2)print(‘cont3=%s‘ % cont3)file.close()结果:cont1=licont2=ne1line2cont3=line3

From the results, the position of the pointer is read from the next position of the last read, when it is read multiple times with the same file.

3.2 ReadLine ()

Used to read an entire line from a file, including the "\ n" character. If a non-negative parameter is specified, the number of bytes of the specified size is returned, including the "\ n" character.

fo = open("allen.txt", "r+")print("文件名为: ", fo.name)line = fo.readline()print("读取第一行 %s" % line)line = fo.readline(5)print("读取的字符串为: %s" % line)fo.close()

Results:

文件名为:  allen.txt读取第一行 line1读取的字符串为: line2
3.3 ReadLines ()

Used to read all remaining unread rows (until the Terminator is EOF) and return the list, not all rows, and return an empty string if the Terminator is encountered.

fo = open("allen.txt", "r+")print("文件名为: ", fo.name)line = fo.readlines(1)print("读取第一行 %s" % line)line = fo.readlines()print("读取剩余行: %s" % line)fo.close()

Results:

文件名为:  allen.txt读取第一行 [‘line1\n‘]读取剩余行: [‘line2\n‘, ‘line3‘]

Using a For loop
Example 1:

fo = open(‘allen.txt‘, ‘r‘)for line in fo.readlines():    print(line)fo.closed

Results:

line1line2line3

Example 2:

fo = open(‘allen.txt‘, ‘r‘)for line in fo.readlines():    print(line.strip())fo.closed

And then look at the results after adding strip ()

line1line2line3

From the above two examples can be seen,readlines () read the time will be a newline character \ n also read out, we need to remove, in fact, read (), ReadLine () is the same

4. File output 4.1 write ()

Writes the specified string to the file.

import osfo = open(‘allen.txt‘, ‘w+‘)while True:    line = input(‘input content‘)  # input不会保留换行符,需要自己加上系统的换行符    if line != ‘.‘:        fo.write(‘%s%s‘ % (line, os.linesep))    else:        breakfor line in fo.readlines():    print(line)fo.close()

If we enter 3 rows separately:

line4line5line6

We had the following three lines in our "Allen.txt" file:

line1line2line3

Plus the 3 lines we entered should be

line1line2line3line4line5line6

Operation Result:

line4line5line6

But the result is not ah, what is the reason? And why we have to add os.linesep ()

Points to note:
1. Files opened in ' w/w+ ' mode will overwrite if the file exists and will be created if the file does not exist.
2, write () and read () do not manipulate line breaks, you need to use the OS module under OS.LINESEP () plus line break, otherwise it will only write on one line

4.2 Writelines ()

Writes a sequence of strings to a file.
This sequence string can be generated by an iterative object, such as a list of strings.
Line breaks need to be made with a newline character \ n.

fo = open(‘allen.txt‘, ‘w+‘)while True:    line = input(‘input content‘)  # input不会保留换行符,需要自己加上系统的换行符    if line != ‘.‘:        fo.writeline(‘%s%s‘ % (line, os.linesep))    else:        breakfor line in fo.readlines():    print(line)fo.close()

We enter 3 lines

line1line2line3

Open File View results:

line1line2line3
5, file Positioning Mobile 5.1 tell ()

Example 1:

fo = open(‘allen.txt‘, ‘r‘)for line in fo.readline():    print(‘本行内容:%s,指针所在的位置:%d‘ % (line, fo.tell()))fo.close()
本行内容:line1,指针所在的位置:6本行内容:line2,指针所在的位置:12本行内容:line3,指针所在的位置:18

Example 2:

fo = open(‘allen.txt‘, ‘r‘)for line in fo.readlines():    print(‘本行内容:%s,指针所在的位置:%d‘ % (line, fo.tell()))fo.close()
本行内容:line1,指针所在的位置:18本行内容:line2,指针所在的位置:18本行内容:line3,指针所在的位置:18

From examples 1 and 2 we can see that readline () reads a line, the position of the pointer moves one line, and ReadLines () is suddenly read to the tail.

5.2 Seek ()

Seek (offset[, whence]): no return value
Offset--offsets, which means the number of bytes to be moved
Whence: Optional, default value is 0. Indicates from which position to start the offset; 0 represents starting at the beginning of the file, 1 representing starting from the current position, and 2 representing the end of the file

fo = open("allen.txt", "r+")line = fo.readline()print("第一次读取的数据为:%s所在的位置为:%d " % (line, fo.tell()))# 重新设置文件读取指针到开头fo.seek(0, 0)line = fo.readline()print("第二次读取的数据为:%s所在的位置为:%d " % (line, fo.tell()))fo.closed
6. File Iteration

The file object is an iterative object that can be iterated using a for loop

fo = open("allen.txt", "r")for content in fo:    print(content)fo.close()
line1line2line3

Strong internal strength of the students, should have found a problem, above all the examples we closed the file is directly close (), imagine, in case of abnormal in the middle, close can not execute, in order to ensure that regardless of errors can be properly closed file, we can use try ... Finally:

try:    f = open(‘allen.txt‘, ‘r‘)    print f.read()finally:    if f:        f.close()

But it's so tedious to write every time, so Python introduces a with statement to help us call the Close () method automatically:

with open(‘allen.txt‘, ‘r‘) as f:    f.read()

is not very concise, there are wood

Python file basic 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.