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
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(“\”, “/”) # 将字符串中含\的转换为/,避免出现特殊字符转换错误的问题
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(“\”, “/”) # 将字符串中含\的转换为/,避免出现特殊字符转换错误的问题
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(“\”, “/”) # 将字符串中含\的转换为/,避免出现特殊字符转换错误的问题
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!