python file operations

1. The Role of File Operations

  • Storing some data allows the program to be used directly the next time it executes without having to make a new copy, which saves time and effort.

2. Basic Operation of Files

2.1 File operation steps
1. Open the file
2,. Read and write operations
3. Close the file
2.1. 1 Open
Using the open function, open an existing file or create a new one.
Grammar:

open(name,mode)

Name: The string that will open the name of the target file (which can include the exact path to the file).
Mode: set the mode of opening the file (access mode): read-only, write, append.

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

# 2. Read and write operations write() read()
f.write('aaa')

# 3. Close close()
f.close()

2.1. 1.1 Open File Mode

Main Access Mode Features

"""
Test Target
1.The impact of access mode on files
2.Access mode pairs write()Impact
3.Can access mode be omitted
"""
# r: Error if file does not exist; Write operation is not supported, meaning read-only
f = open('test.txt', 'r')
f.close()
# w: Write only; File does not exist, create a new file, if you write, it will overwrite the original content
f = open('1.txt', 'w')
f.write('bbb')
f.close()
# A: append; If the file does not exist, create a new file; Add new content based on the original content
f = open('2.txt', 'a')
f.write('xyz')
f.close()
# Access mode parameter can be omitted if omitted means access mode is r
f = open('1.txt')
f.close()

Access Mode Feature 2

"""
Target Setting
1.r+ and w+ a+ Difference
    r No error with this file
    w If there is no file, it will be created.
    a No file will create a new file
2.The effect of file pointer on data reading
    r+ The file pointer starts, so you can read the data
    w+ File pointer at the beginning, overwrite the original with new content
    a+ The file pointer is at the end and cannot read data (there is no data behind the pointer)
"""
f=open('test.txt','r+')
con=f.read()
print(con)
f.close()

f = open('test.txt', 'w+')
con = f.read()
print(con)
f.close()

f = open('test.txt', 'a+')
con = f.read()
print(con)
f.close()

2.1. 2.2 Read

  • read()

File object. read(num)

Num denotes the length (in bytes) of the data to be read from the file, and if no num is passed in, it means reading all the data in the file.

f = open('test.txt', 'r')
# If the file content is wrapped, with \n at the bottom, there will be byte placeholders, resulting in mismatches between the parameters and values seen by the eyes reading the read writing parameters
# Read does not write parameter means read all
print(f.read())
print(f.read(10))
f.close()
  • readlines()
    readlines can read the entire file one-time in a row fashion and return a list where
    The data in each row is an element.
f = open('test.txt', 'r')
con = f.readlines()
print(con)
f.close()
  • readline()
    readline() reads one line at a time
f = open('test.txt', 'r')
con = f.readline()
print(f'first line{con}')
con = f.readline()
print(f'Second line{con}')
f.close()

2.1.2.3seek()
Role: Used to move file pointers
Grammar:

File object. seek (offset, starting position)

Start position:

  • 0: Beginning of file
  • 1: Current location
  • 2: End of file
"""
Syntax: File object.seek(Offset, Start Position) 0 Start 1 Current 2 End
 Goal:
    1.r Change the file pointer position: Change the start of reading data or place the file pointer at the end (data cannot be read)
    2.a Change file pointer position so that data can be read out
"""
# f = open('test.txt', 'r+')
f = open('test.txt', 'a+')
# 1. Change the start of reading data
# f.seek(2, 0)
# 1. Put the file pointer at the end (unable to read data)
# f.seek(0,2)

# 2.a Change file pointer position so that data can be read out
# f.seek(0,0)
f.seek(0)
con = f.read()
print(con)
f.close()

3. File Backup

Requirements: User input Currently record any file name, and the program completes the backup function for the file (backup file name is xx [backup] suffix, for example: test [backup].txt).

Step 3.1

  1. File name to receive user input
  2. Planning Backup File Name
  3. Backup File Write Data

3.2 Code implementation

# 1. User input target file
old_name = input('Please enter the name of the file you want to back up:')
# 2. Name of planning backup file
#     2.1 Extract Target File Suffix - Dot separates name from suffix - Right-most dot followed by suffix - String Find Substring rfind
index = old_name.rfind('.')
# Determine whether it is an invalid file. txt
if index > 0:
    #     Extract Suffix
    postfix = old_name[index:]
#     2.2 File name of organization backup, original name +[backup] + suffix
# The original name is a subset of the string--a slice[Start: End: Step]
new_name = old_name[:index] + '[backups]' + postfix
print(new_name)
# 3. Backup files write data (data is the same as the original)
#   3.1 Open source and backup files
old_f = open(old_name, 'rb')
new_f = open(new_name, 'wb')
#   3.2 Write source file data to backup file
# If the target file size is uncertain, the loop reads and writes, and when the read data does not end the loop
while True:
    con = old_f.read(1024)
    if len(con) == 0:
        #     Read complete
        break
    new_f.write(con)
# 3.3 Close Files
old_f.close()
new_f.close()

4. Operation of Files and Folders

Files and folders in python operate with the help of the related functions in the os module.

4.1 File Rename

Os. Rename (target file, new file name)

# rename() --Rename folder
import os
os.rename('aa','jj')

4.2 Delete Files

Os. Remove (target file)

"""
1.Import Module os
2.Use in-module functionality
"""
import os

# 1.rename(): Rename
os.rename('1.txt', '10.txt')
# 2.remove(): Delete the file
os.remove('10.txt')

4.3 Create folders

Os. MKDIR (folder name)

4.4 Delete folders

Os. Rmdir (folder name)

4.5 Get Current Directory

os.getwd()

4.6 Change default directory

Os. Chdir (directory)

4.7 Get Directory List

Os. Listdir (directory)

import os
os.mkdir('aa')
os.rmdir('aa')
print(os.getcwd())
# chdir(): Change directory path
# Requirements: Create bb folder in AA directory: 1. Switch directory to aa,2. Create bb
os.mkdir('aa')
os.chdir('aa')
os.mkdir('bb')
# listdir(): Get all the files under the touch folder and return a list
print(os.listdir())
print(os.listdir('aa'))

5. Application Cases

Requirement: Modify file name in batch to add specified string and delete specified string

Keywords: Python Pycharm Pytorch

Added by thiago_ on Tue, 14 Dec 2021 20:02:03 +0200