SoFunction
Updated on 2024-11-17

Python File Handling

This article gives you an introduction to Python file processing related knowledge, the details are as follows:

1. Common operations of the file

Files are a common operation in everyday programming, usually used to store data or parameters of the application system. python provides os,, shutil and other modules to deal with files, including the most commonly used functions to open files, read and write files, assign files and delete files.

1.1 Creation of documents

The global file() function from python2 has been removed from python 3.+, and the open() function has been retained. Files can be opened or created using the open() function. This function allows you to specify the processing mode and set the open file to read-only, write-only, or read-write state. open() is declared as follows:

open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)

Parameter Description:

The -file parameter is the name of the file being opened. If the file file does not exist, open() creates a file named name and then opens that file.

The -parameter mode refers to the opening mode of the file. Please refer to the following for the opening mode of the file.

The -parameter buffering sets the caching mode. 0 means no caching, 1 means caching; if it is greater than 1, it indicates the size of the buffer in bytes.

The -encoding parameter sets the character encoding format of the file.

The -open() function returns a file object, which can perform various operations on the file File mode:

'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing

Create a new file, open it and write

'a' open for writing, appending to the end of the file if it exists

Open the file in mode to append

'b' binary modeBinary mode open,Can be used with other modes
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)All line breaks are supported

Note: Files such as pictures, videos, etc. must be read and written using the b mode.

message = '''
hello world,\n
hello python,\n
good time.
'''
f = open('','w')
(message)
()

Code Description:

-Define a string variable

-Creates a file in write-only mode and writes to the

-Writing string variables to a file

-Close file

1.2 Reading of documents

There are several ways to read a file, you can use the readline(), readlines(), or read() function to read a file.

1. Read line by line readline()

readline() reads the file one line at a time, and needs to loop through the file. However, when the file pointer moves to the end of the file, an error will occur if readline() is still used to read the file. Therefore, the program needs to add a judgment statement to determine whether the time pointer is at the end of the file, and interrupt the loop through the statement. The example is as follows:

# Read a file using readline mode
f = open('','r')
while True:
line = ()
if line:
print(line)
else:
break
()
#in the event thatline = (2)then it means that only two bytes are read in each loop,Until the end of the line

2. Read multiple lines readlines()

# Read files on multiple lines
f = open('')
lines = ()
for line in lines:
print(line)
()

3. One-time reading method read()

The simplest way to read a file is to use read(), read() will read all the contents of the file at once, and assigned to a string variable, but when the file is relatively large it is not recommended to use read() to read the file, because reading a relatively large content will consume a large amount of memory, affecting the performance of the system. The example is as follows:

# Read the files one at a time
f = open('','r')
lines = ()
print(lines)
()

File pointer:

with open('','rb') as src:
rd = (100)
print(rd)
print((()))
rd = (100)
print(rd)
print((()))
#Each reading100nibbles,Then return the position of the pointer

function (math.)

Usually we use open () to open a file and assigned to a string variable to operate on the file, and finally need to manually close the file, so that write up a bit of trouble, the following we can use the with function to open and close the file to write a function on a line.

with open('','r') as src:
da = ()
print(da)
#Open the file in read-only mode and assign the valuesrc,Then just manipulate the file,Code and Useopen()to manipulate files in the same way。

1.3 Writing of documents

There are several ways to write a file, you can use write(), you can also use writelines() method to write a file. write() can write a string to a file, writelines() can write a list to a file. The example is as follows:

m1 = 'hello world'
l1 = ['good','time']
f = open('','w')
(m1)
(l1)
()

Appenditions to the document:

m1 = 'hello python'
f = open('','a+')
(m1)
()

1.4 Deletion of documents

File deletion requires the use of os modules and modules, os modules provide the system's environment, files, directories and other operating system functions. For files more commonly used os module functions are as follows:

-(path,mode)#Access with the permissions specified by mode.
-(path,mode)# Changes the access permissions of a file, mode is expressed in UNIX permissions notation.
-(filename,flag[,mode=0777])# Open the file with the permissions specified by mode. By default, all users are given read, write, and execute permissions
-(path)# Delete the file specified by path.
-(old,new)# Rename a file or directory, old means original file or directory, new means new file or directory.
-(path)# Returns all attributes of the file specified by path.
-(path)# Returns all attributes of the open file.
-(filepath[,operation])# Start the associated program to open the file. For example, to open an html file, it will start Internet Explorer.
-()# Create a temporary file, which is created in the operating system's temporary directory.

Note: The open() function of the os module is used differently than the built-in open() function.

The functions commonly used by the module are as follows:

-(path)# Returns the absolute path where path is located.
-(path)# Returns the path of a directory.
-(path)# Determine if the file exists.
-(filename)# Returns the last time the file was accessed.
-(filename)# Returns the creation time of the file.
-(filename)# Returns the last modification time of a file.
-(filename)# Returns the size of the file.

judgment function

-(s)# Test if the path is an absolute path
-(path)# Determine if path is a directory.
-(path)# Determine if the path is a file.
-(p)# split the path and return it as a list
-(p)# Split the file extension from the path
-(p)# Split the name of the drive from the path
-(top,func,arg)# Traverse the directory tree

Examples are shown below:

import os
if ('../'):
('')
print('is del')
else:
print('no')

1.5 Reproduction of documents

There are several ways to copy files, here we look at the first low way, is to read and write the way to copy files. The example is as follows:

# Use read(), write() to implement file copying
f1 = open('','r')
f2 = open('','w')
(())
()
()

The second method:

shutil module, shutil module is another file, directory management interface, provides a number of functions for copying, directory. copyfile() function can be implemented to copy the file, copyfile() function is declared as follows:
(src,dst)
-src indicates the path to the source file, src is of string type
-dst indicates the path to the target file, dst is of string type
-copy the file pointed to by src to the file pointed to by dst

Examples are shown below:

import shutil
('','')

1.6 Renaming of documents

The rename() function of the os module renames a file or directory.

import os
('','')

File renaming can also be accomplished using the move() function in shutil.

import shutil
('','')

Modify the file's suffix:

import os
files = ('.')
for filename in files:
li = (filename)# Returns a list of post filenames and suffixes
if li[1] == '.html':
newname = li[0] + '.htm'
(filename,newname)

The glob module is used to match paths and return a list of files that meet the given conditions. the main function of the glob module is glob(), which returns multiple files that meet the same matching conditions. The above presentation needs to determine whether the html suffix, you can also use the glob () function to directly match the file name. Matching code is as follows.

('*.html')

glob can also do more pairwise matching of paths. For example, match all text files in a directory beginning with w on the C drive.

('C:\\\w*\\*\\txt') 

1.7 Search and Replacement of Documents

Search and Replacement of file contents can be accomplished using Find and Replace of strings. For example, find the string 'hello' in a file and count the number of times 'hello' appears. The code is as follows:

python, equal to anything!

The above content gives you the knowledge related to Python file processing, I hope it will help you!