search
HomeBackend DevelopmentPython Tutorialpython file operation method

python file operation method

Mar 30, 2018 pm 04:18 PM
pythonoperatemethod

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)

相关推荐:

Python 操作 MySQL 的正确姿势

The above is the detailed content of python file operation method. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

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.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

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.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software