The fourteenth introduction to Python — file operation

Time:2020-5-16

1、 Basic operation of files

1. Open file

  • open(name,mode)  
  • Name – file name string;Mode access mode

P.s:Access mode

r

Read only. File pointer at beginning of file, default mode

P. S: no file error is reported when opening

rb Binary open file for read-only, file pointer at the beginning of the file
r+

Read write, the file pointer is at the beginning of the file

P. S: R + open nonexistent file error, the same as R operation

rb+ Binary open file for reading and writing, file pointer at the beginning of the file
w

Write only, the file pointer is at the beginning of the file.

If the file already exists, editing from the beginning will overwrite the original content, i.e. delete the original content; if the file does not exist, create a new file

wb

Binary open files are used for writing.

The rules are the same as’ W ‘.

w+

Read and write.

Writing rules are the same as’ W ‘

P. S: W + open the file to delete the original content. If it is not written, it will be read as empty directly, because the w operation will overwrite the original content

wb+

Binary open file for reading and writing

Same as’ W + ‘

a

Append, the file pointer is at the end of the file.

If the file already exists, add it after the original content; if the file does not exist, create a new file

ab Binary open file is used for appending, others are the same as’ a ‘
a+

Binary open file is used for reading and writing. The write rule is the same as’ a ‘

P. S: a + is empty when it is not written, because the file of a operation is at the end of the file

ab+ Binary open file is used for reading and writing. The write rule is the same as’ a ‘

2. Read file

read(num)

Read from the beginning. Num is the length of the read data. Read all without writing

f = open('test.txt', 'r')
Content = f.read (7) ා P.S: line feed occupies one character
print(content)
"""
aaaaa
b
"""
f.close()
readlines()

Read from the beginning according to the row, read the data and store it in the list. The data in each row is an element

f = open('test.txt', 'r')
content = f.readlines()  
print(content)  # ['aaaaa\n', 'bbbbb\n', 'ccccc']
f.close()
readline()

Read one line at a time

f = open('test.txt', 'r')

content = f.readline()
print(content)  # aaaaa

content = f.readline()
print(content)  # bbbbb

f.close()

3. Write file: f.write()

4. Move cursor: f.seek (offset, start position)

In the starting position:

  • 0: beginning of file
  • 1: Current location
  • 2: End of file
f = open('test.txt','r')
f.seek(2,0)
con=f.read()
print(con)
'''
aaa
bbbbb
ccccc
'''
f. Seek (0) ා seek (0) is short for seek (0,0)
con=f.read()
print(con)
'''
aaaaa
bbbbb
ccccc
'''
f.close()

2、 Application case – backup file:

#User input
Old_name = input ('Please input the file name to be backed up: ')
#The filename is changed to a new name by truncating the name and suffix
index = old_name.rfind('.')
if index <= 0:
    Print ('malformed filename! ')
else:
    New_name = old_name [: index] + 'replica' + old_name [index:]
    #File write
    old_file = open(old_name, 'rb')
    new_file = open(new_name, 'wb')
    while True:
        content = old_file.read(1024)
        if len(content)==0:
            Print ('backup succeeded! )
            break
        new_file.write(content)
    new_file.close()
    old_file.close()

3、 Operation of files and folders:

1. Premise: import OS module

import os

2. Functions

Rename files and folders Os.rename (target filename, new filename)
Delete file Os.remove (target filename)
create folder Os.mkdir (folder name)
remove folders Os.rmdir (folder name)
Get current path os.getcwd()
Change default path Os.chdir (path)
Get the list of files in the directory Os.listdir (directory)

3. Application cases

 

import os
Print (OS. Getcwd()) ා get the current path C: \ users \ MYUSERNAME \ pycharmprojects \ demo
Os.mkdir ('folder ') ා new folder
#OS. Remove ('folder ') ා deleted folder, error reported
os.chdir ('folder') (toggle path
Print (OS. Getcwd()) ා get the current path C: \ users \ MYUSERNAME \ pycharmprojects \ demo\文件夹
i = 5
while i > 0:
    open('file' + str(i) + '.txt', 'w')
    i -= 1
#Create 5 files (file1.txt ~ file5.txt) under the folder