Python Learning Notes file operation

Keywords: Python

Python learning notes (17) file operation

1, Concept and function of file operation

Thinking: what does file operation include?

Answer: open, close, read, write, copy

Thinking: what is the function of document operation?

Answer: read content, write content, backup content

2, Basic operation of files

2.1 document operation steps

  1. Open file
  2. Reading and writing
  3. Close file
Note: you can only open and close files without any read-write operation.
2.1.1 open

2.1.2 document object method

2.1.2.1 write

f.write('Write contents')

2.1.2.2 read

  • read()
File object. read(num)

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

# If the contents of the file wrap, and there are \ n bytes in the bottom layer, the number of bytes read out of the read writing parameters does not match the parameter value
# read() does not write parameters, which means reading all
print(f.read(10))
f.close()

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

print(f.readlines())
f.close()

  • readline()
    readline() reads one line at a time.
f = open('test.txt','r')

print(f.readline())  #The first call to readline reads the first line of the file
print(f.readline())  #The second call to readline reads the second line of the file
print(f.readline())  #The third call to readline reads the third line of the file
print(f.readline())  #The fourth call to readline reads the fourth line of the file
print(f.readline())  #The fifth call to readline reads the contents of line 5 of the file

f.close()


2.1.2.3 seek()

Function: used to move file pointer

The syntax is as follows:

File object. Seek (offset, start)

Starting position:

  • 0: beginning of file
  • 1: Current location
  • 2: End of file
'''
//Syntax: seek (target offset, start position) start position: 0 -- start, 1 -- current position, 2 -- end
//Objectives:
   1. r Change file pointer position: change the start position of reading data or end the file pointer position (unable to read data)
   2. a Change the file pointer position so that the data can be read
'''

# 1. r+ :
f = open('test.txt','r+')
print(f.read())  # Read the target file all

f.seek(2,0)   # Indicates 2 bytes offset to the right, starting at the beginning
print(f.read())  # Read from the third data in the target file

f.seek(0,2)  # Indicates no offset, starting at the end
print(f.read())  # Read from the end of the file, so no data can be read

f.close()

# 2. a+ :
f = open('test.txt','a+')
print(f.read())  #File pointer cannot read data at the end

f.seek(0,0)  # Indicates no offset, starting at the beginning
print(f.read())  # Read from beginning of file

f.close()

2.1.3 shut down
File object name. close()

Example:

# 1. open()
f = open('test.txt','w')

# 2. Read / write write() read()
f.write('aa')

# 3. close()
f.close()

2.2 file operation access mode

Be careful:

  1. With 'b' is in binary form;
  2. With '+', it is readable and writable.
'''
//Test objectives:
4. Impact of access mode on files
5. Access mode pair write()Influence
6. Whether access mode can be omitted
'''

# r: If the file does not exist, an error will be reported: write operation is not supported, indicating read-only
f = open('test.txt','r')
f.write('aa')  # Report wrong
f.close()

# w: Write only: if the file does not exist, create a new file: if write is performed, the original content will be overwritten
f = open('1.txt','w')
f.write('aaaaa')  # Will overwrite the original content
f.close()

# A: append: if the file does not exist, create a new file: if write is performed, append the new content based on the original content
f = open('2.txt','a')
f.write('abb')  # New content will be added to the original content
f. close()

# Whether the access mode can be omitted. If omitted, it means that the access mode is r
f = open('1.txt')
f.close()
'''
//Test objectives:
1. r+ / w+ / a+ / Difference:
2. The effect of file pointer on data reading
'''

# r+: if there is no such file, an error will be reported; the file pointer is at the beginning, so the data can be read
# f = open('test1.txt','r+')  # Wrong report, because no
f = open('test.txt','r+')
print(f.read())
f.close()

# w +: no new file is created for this file; the file pointer is at the beginning, and the original content is overwritten with the new content
f = open('test1.txt','w+')
print(f.read())
f.close()

# a +: no new file is created for this file; the file pointer is at the end, unable to read the data (no data after the file pointer)
f = open('test.txt','a+')
print(f.read())


Note: the result of this screenshot is only the result of opening the file in the form of r +.

3, File backup

3.1 steps

3.2 code implementation

Be careful:

# 1. User input target file
old_name = input('Please enter the file name to back up:')

# 2. Name of planning backup file
 # 2.1 extract the suffix of the target file -- find '.' in the name -- separate the name and suffix -- the rightmost '.' is the suffix '.' -- find a substring rfind()
index = old_name.rfind('.')  # Extract the subscript of suffix '.'

 # 2.2 file name of organization backup = original name + [backup] + suffix
 # The original name is a part of the string -- just slice the string -- slice [start: end: step length]
if (index > 0):
    print('The name of the original document is:',old_name[:index])  # Extract original name
    print('The suffix of the original file name is',old_name[index:])  # Extract suffix
    new_name = old_name[:index] + '[backups]' + old_name[index:]
    print('The backup file name is:',new_name)

# 3. Write data to backup file (the data is the same as the source file)
 # 3.1 open the original file and backup file
old_f = open(old_name,'rb')
new_f = open(new_name,'wb')

 # 3.2 original file reading and backup file writing
#If the target file size is not determined, read and write circularly. When the read data does not terminate the cycle
while True:
    con = old_f.read(1024)
    if len(con) == 0:
        break
    new_f.write(con)
 # 3.3 closing documents
old_f.close()
new_f.close()

4, Operation of files and folders

The operation of files and folders in python depends on the relevant functions in the os module. The specific steps are as follows:

  1. Import os module
import os
  1. Use os module related functions
os. Function name ()
4.1 rename(): Rename
os.rename('Old file name','New file name')

Note: rename() can also be used to rename file names

# rename(): can also be used to rename a folder -- rename folder aa to aaaa
os.rename('aa','aaaa')
4.2 remove(): delete
os.remove('file name')
'''
4. Import module os
5. Using in module functions
'''
import os
# 1. rename(): Rename
os.rename('2.txt','20.txt')  # After the operation, the file is renamed

# 2. remove(): delete file
os.remove('20.txt')  # After the operation, the file is deleted
4.3 creating folders
Os.mkdir (folder name)
4.4 delete folder
Os.rmdir (folder name)
4.5 get current directory path
os.getcwd()  # C:\Users\YSH\Desktop\test
4.6 change the default directory
Os.chdir (folder name)

Example 1:

# 5. chdir(): change directory path
os.mkdir('aa')
# Requirement: create bb folder in aa folder: 1. Switch directory to aa 2. Create bb
os.chdir('aa')
os.mkdir('bb')


Example 2:

# Quick Resume in a large folder several small files
import os
os.chdir('aaaa')
os.mkdir('cc')
os.mkdir('dd')
os.mkdir('ee')
os.mkdir('ff')
os.mkdir('gg')
os.mkdir('hh')
os.mkdir('ii')

4.7 get directory list
Os.listdir (folder name)
# listdir(): get all the file names under a folder and return a list
print(os.listdir('aa'))  #['bb']

5, Application cases



Add rename:

# Requirement 1: rename all files in the test folder from xxxx to python
import os
# 1. Find all files: read the directory list of aaaa folder -- listdir()
file_list = os.listdir()
print(file_list)

# 2. Construction name
for i in file_list:
    # New_name ='python '+ original filename
    new_name = 'Python_' + i

# 3. renaming
    os.rename(i,new_name)

Delete rename:

# Requirement 2: rename all files in the test folder from Python ﹣ xxxx to xxxx
import os
# 1. Find all files: read the directory list of aaaa folder -- listdir()
file_list = os.listdir()
print(file_list)

# 2. Construct a new name
for i in file_list:
    num = len('Python_')
    new_name = i[num:]

# 3. renaming
    os.rename(i,new_name)

Six, summary


Published 21 original articles, praised 0, visited 1326
Private letter follow

Posted by BrianWald on Sat, 15 Feb 2020 19:41:16 -0800