Python文件操作

目录

1 Open a file

2 Write a file

3 Close a file

4 Append to a file

5. Read a file

6. Read a file line by line

7. Python读写二进制文件


1 Open a file

        语法:file_object = open("filename", "mode")

        文件名可以带路径。

        'mode'用于操作模式:

ModeDescription
‘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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笨牛慢耕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值