目录
1 Open a file
语法:file_object = open("filename", "mode")
文件名可以带路径。
'mode'用于操作模式:
Mode | Description |
---|---|
‘r’ | This is the default mode. It Opens file for reading. |
‘w’ | This Mode Opens file for writing. If file does not exist, it creates a new file. If file exists it truncates the file. |
‘x’ | Creates a new file. If file already exists, the operation fails. |
‘a’ | Open file in append mode. If file does not exist, it creates a new file. |
‘t’ | This is the default mode. It opens in text mode. |
‘b’ | This opens in binary mode. |
‘+’ | This will open a file for reading and writing (updating) |
注意,'+'的作用是同时以读写模式打开(The + tells the python interpreter for Python open text file with read and write permissions.)。所以'w+'的意思是以写模式打开,但是也可以读取(?待确认)。通常只见过"w+","a+",并没有见过"r+".
2 Write a file
语法:f.write()
f= open("myfile.txt","w+")
for i in range(4):
f.write("This is line %d\n" % (i+1))
f.close()
打开myfile.txt可以看到:
3 Close a file
语法:f.close()
4 Append to a file
f= open("myfile.txt","a+")
for i in range(4):
f.write("Appended line %d\n" % (i+1))
f.close()
5. Read a file
f=open('myfile.txt','r')
if f.mode == 'r':
contents = f.read()
print(contents)
f.close()
用选项"r"表示以读模式打开文件,检查是否是读模式(非必须) ,如果是读模式就读取内容,并打印出来。在运行窗口输出结果:
注意,以上读操作是将整个文件一股脑地读取并存储在一个字符串变量中。用type(contents)可以看到返回类型“str”。
那如果想按行读入(即将内容按行分割读取)呢,看下节:
6. Read a file line by line
要逐行读入,而不是一股脑地读入的话,用readlines()函数。
print('Read line by line...')
f=open('myfile.txt','r')
if f.mode == 'r':
f_lines = f.readlines()
for line in f_lines:
print(line)
f.close()
当然,readlines()还是一次性地将所有数据全部读入,但是它按行分割进行存放,使得后续使用起来会很方便。对于想本例这样的简单的文件,看不出什么差别,但是对于存放复杂数据格式的文件,使用reanlines()将会使后续数据处理和利用变得非常方便。
用type(f_lines)检验会发现f_lines是一个列表,其中每个元素就是文件的一行的内容。
7. Python读写二进制文件
import random
f = open('binary_file', 'w+b')
byte_arr = [random.randint(0,255) for k in range(10)]
print(byte_arr)
binary_format = bytearray(byte_arr)
f.write(binary_format)
f.close()
f = open('binary_file', 'rb')
while True:
b_read = f.read(1)
if b_read == b'':
print('read file complete!')
break
else:
print("{0}".format(b_read))
这段代码运行结果如下:
[182, 200, 200, 177, 231, 227, 58, 204, 253, 151]
b'\xb6'
b'\xc8'
b'\xc8'
b'\xb1'
b'\xe7'
b'\xe3'
b':'
b'\xcc'
b'\xfd'
b'\x97'
read file complete!
更多的Python小伎俩参见: Python tips (动态更新中)https://blog.csdn.net/chenxy_bwave/article/details/120219722
关于Python的csv文件访问也可参考:Pandas读取CSV和普通文本数据文件https://blog.csdn.net/chenxy_bwave/article/details/121176698https://blog.csdn.net/chenxy_bwave/article/details/121176698