python file operation method
This article mainly introduces you to python file operations and simple copy and backup. I hope it can help you.
1.open function
Everything in python is an object, so the normal process for us to open a file is
1. Select the file-open the file-edit, copy, delete and other operations- To close the file
put it in python and use code:
f = open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
f.close()
where file is the absolute path of the file plus the file name, mode is the file reading method, the default is r, which is read-only mode, and the optional
mode in the source code is interpreted as
‘r’ open for reading (default) ‘w’ open for writing, truncating the file first ‘x’ create a new file and open it for writing ‘a’ open for writing, appending to the end of the file if it exists ‘b’ binary mode ‘t’ text mode (default) ‘+’ open a disk file for updating (reading and writing) ‘U’ universal newline mode (deprecated)
It is recommended that you read the source code: the translation is:
r Open the file in read-only mode. The file pointer will be placed at the beginning of the file. This is the default mode.
rb Open a file in binary format for reading only. The file pointer will be placed at the beginning of the file. This is the default mode.
r+ Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+ Opens a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
w Open a file for writing only. If the file already exists, it is overwritten. If the file does not exist, create a new file.
wb Open a file in binary format for writing only. If the file already exists, it is overwritten. If the file does not exist, create a new file.
w+ Open a file for reading and writing. If the file already exists, it is overwritten. If the file does not exist, create a new file.
wb+ Opens a file in binary format for reading and writing. If the file already exists, it is overwritten. If the file does not exist, create a new file.
a Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, new content will be written after existing content. If the file does not exist, create a new file for writing.
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, new content will be written after existing content. If the file does not exist, create a new file for writing.
a+ Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file will be opened in append mode. If the file does not exist, a new file is created for reading and writing.
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, a new file is created for reading and writing.
Here we have to call the f.close method every time we open the file. It is troublesome and easy to forget. Let’s use with to optimize it here:
with open(“E:\githubproject\Source-code\basis\file\test. txt", mode='r') as f:
pass
Here f is equivalent to opening the file, but the file is not read at this time, that is, the file is not placed in the memory. f has many built-in methods, the more commonly used one is f.write()
Here We use fwrite to copy files:
with open(“E:\githubproject\Source-code\basis\file\test.txt”, mode='r') as f:
contents = f.read()
with open(“E:\githubproject\Source-code\basis\file\test_bak.txt”, mode=’w’) as f_bak:
f_bak.write(contents)
But this method needs to be written every time, so we use a function to encapsulate the file name.
def cp(path):
with open(path, ‘r’) as f:
data = f.read()
Filename = path[0:path.rindex(“.”)] # Obtain the previous string (i.e. file name) through the rindex method
ext = path[path.rindex(“.”):] # Obtain the string after . (i.e. file suffix) through the rindex method
With open(“%s_bak%s” % (filename, ext), ‘w’) as f_bak: # Open and operate the new file named _bak
f_bak.write(data)
path = “E:\githubproject\Source-code\basis\file\test.txt”
path = path.replace(“\”, “/ ”) # Convert characters containing \ in the string to / to avoid special character conversion errors
path = '/'.join(path.split('\')) #Similar to the above method , but special characters cannot be converted yet...
cp(path)
The problem of combining file name and path into special characters in Windows has not been solved yet
When we call the read method, the file will be Write to memory, but what if we want to copy a large file, such as 10 G?
Python file operation has a pointer, that is, when we read somewhere, the pointer It will point to the place of read. When we read(), the file points to the end. When read(100), the pointer points to 100. The next time read will read from here, f.seek(0, 0) will be The pointer returns to its initial position. We can use the pointer to read multiple times to copy the large file:
def cp(path): filename = path[0:path.rindex(“.”)] # 通过rindex方法取得.之前的字符串(即文件名) ext = path[path.rindex(“.”):] # 通过rindex方法取得.之后的字符串(即文件后缀) with open(path, ‘r’) as f, open(“%s_bak%s” % (filename, ext), ‘a’) as f_bak: while True: data = f.read(1024) print(data) f_bak.write(data) if len(data) == 0: break path = “E:\githubproject\Source-code\basis\file\test.txt” path = path.replace(“\”, “/”) # 将字符串中含\的转换为/,避免出现特殊字符转换错误的问题
path = ‘/’.join(path.split(‘\’)) #与上方法类似,但是还无法转换特殊字符…
cp(path)
这篇文章主要介绍了python操作文件,以及简单的复制备份.
1.open函数
python中一切皆对象,所以正常我们打开一个文件的过程是
1.选中文件-打开文件-编辑,复制,删除等操作-关闭文件
放到python中用代码实现就是:
f = open(file, mode=’r’, buffering=None, encoding=None, errors=None, newline=None, closefd=True):
f.close()
其中file是文件的绝对路径加文件名,mode是文件读取方式,默认为r即只读方式,后面的选填
mode在源码的解释为
‘r’ open for reading (default) ‘w’ open for writing, truncating the file first ‘x’ create a new file and open it for writing ‘a’ open for writing, appending to the end of the file if it exists ‘b’ binary mode ‘t’ text mode (default) ‘+’ open a disk file for updating (reading and writing) ‘U’ universal newline mode (deprecated)
建议大家看源码:翻译过来就是:
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
w 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
w+ 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。
这里我们每次打开file都要调用f.close方法比较麻烦也容易忘,这里用with优化一下:
with open(“E:\githubproject\Source-code\basis\file\test.txt”, mode=’r’) as f:
pass
这里f就相当于打开了文件,但是此时并没有读取文件,即没有把文件放到内存中,f有很多内置方法,比较常用的是f.write()
这里我们使用fwrite来实现文件的复制:
with open(“E:\githubproject\Source-code\basis\file\test.txt”, mode=’r’) as f: contents = f.read() with open(“E:\githubproject\Source-code\basis\file\test_bak.txt”, mode=’w’) as f_bak: f_bak.write(contents) 但是这个方法每次都要写,所以我们用个函数把文件名封装进进去. def cp(path): with open(path, ‘r’) as f: data = f.read() filename = path[0:path.rindex(“.”)] # 通过rindex方法取得.之前的字符串(即文件名) ext = path[path.rindex(“.”):] # 通过rindex方法取得.之后的字符串(即文件后缀) with open(“%s_bak%s” % (filename, ext), ‘w’) as f_bak: # 新建文件名_bak的文件打开并操作 f_bak.write(data) path = “E:\githubproject\Source-code\basis\file\test.txt” path = path.replace(“\”, “/”) # 将字符串中含\的转换为/,避免出现特殊字符转换错误的问题
path = ‘/’.join(path.split(‘\’)) #与上方法类似,但是还无法转换特殊字符…
cp(path)
目前还没解决windows中文件名加路径组合成了特殊字符的问题
我们调用read方法的时候会将文件写入内存,但是如果我们要复制一个很大的文件,比如有10个G的时候怎么办呢,
python文件操作有个指针的说法,即当我们read到某处的时候,指针就会指到read的地方,当我们read()的时候,文件就指向了末尾,当read(100),指针即指向100,下次read再从此处读取,f.seek(0, 0)即将指针回到初始位置,我们可以利用指针来多次读取实现大文件的复制:
def cp(path): filename = path[0:path.rindex(“.”)] # 通过rindex方法取得.之前的字符串(即文件名) ext = path[path.rindex(“.”):] # 通过rindex方法取得.之后的字符串(即文件后缀) with open(path, ‘r’) as f, open(“%s_bak%s” % (filename, ext), ‘a’) as f_bak: while True: data = f.read(1024) print(data) f_bak.write(data) if len(data) == 0: break path = “E:\githubproject\Source-code\basis\file\test.txt” path = path.replace(“\”, “/”) # 将字符串中含\的转换为/,避免出现特殊字符转换错误的问题
path = ‘/’.join(path.split(‘\’)) #与上方法类似,但是还无法转换特殊字符…
cp(path)
相关推荐:
The above is the detailed content of python file operation method. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

This article will explain how to improve website performance by analyzing Apache logs under the Debian system. 1. Log Analysis Basics Apache log records the detailed information of all HTTP requests, including IP address, timestamp, request URL, HTTP method and response code. In Debian systems, these logs are usually located in the /var/log/apache2/access.log and /var/log/apache2/error.log directories. Understanding the log structure is the first step in effective analysis. 2. Log analysis tool You can use a variety of tools to analyze Apache logs: Command line tools: grep, awk, sed and other command line tools.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

This article discusses the DDoS attack detection method. Although no direct application case of "DebianSniffer" was found, the following methods can be used for DDoS attack detection: Effective DDoS attack detection technology: Detection based on traffic analysis: identifying DDoS attacks by monitoring abnormal patterns of network traffic, such as sudden traffic growth, surge in connections on specific ports, etc. This can be achieved using a variety of tools, including but not limited to professional network monitoring systems and custom scripts. For example, Python scripts combined with pyshark and colorama libraries can monitor network traffic in real time and issue alerts. Detection based on statistical analysis: By analyzing statistical characteristics of network traffic, such as data

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){
