python 对文件进行操作(读取/路径/写入/修改/储存/附加)

您所在的位置:网站首页 修改文件读写 python 对文件进行操作(读取/路径/写入/修改/储存/附加)

python 对文件进行操作(读取/路径/写入/修改/储存/附加)

2024-07-17 10:29| 来源: 网络整理| 查看: 265

1 从文件读取数据 1.1 读取整个文件 with open("./test_file.txt") as file_object: content = file_object.read() print(content)

with 关键字 用于不再访问文件时将其关闭; 可以使用open()与close()来访问文件; file_object.read() 用于读取文件内容,以str形式储存在变量content里; 打印content可以讲文件的内容打印出来;

1.2 文件路径 # linux path = "/home/user/python_file/test.txt" # windows path = "C:\\Users\\my_file\\test.txt"

windows操作系统下用“\”,Linux和OS X系统下用“/”隔开文件夹;

1.3 逐行读取 file_name = "test.txt" with open(file_name) as file_object: for line in file_object: print(line) # 此时行与行之间会有空行,因为打印了换行符 print(line.rstrip()) # 此时没有空行

按行打印文件内容;

1.4 用列表储存文件各行内容 filename = "test.txt" # 储存 with open(filename) as file_object: lines = file_object.readlines() # 打印 for line in lines: print(line.rstrip())

读取文本时,python将文本理解为str形式; 如果读取数字,并将作为数值使用,需要int()或float();

2 写入文件 2.1 写入空文件 filename = "./new_file.txt" with open(filename, 'w') as file_object: file_object.write("this is a new file")

如果open的文件名不存在,那就创建; 如果是(‘w’)写入,如果之前已经存在该文件,则会清空;

w 写入模式a 追加模式r 读取模式r+ 读取和写入模式wb 字节写入模式w+ 文本写入模式rb 以二进制方式读取文件。该文件必须已存在。 2.2 写入多行 file_object.write("this is a new file\n")

添加换行符;

2.3 附加到文件

附加模式:不覆盖原有内容,给文件添加内容;

with open(filename, 'a') as file_object: file_object.write("this is add content\n") 3 存储数据

使用json模块储存数据; json的全称是Java Script Object Notation,即JS 对象简谱;

import json # 使用 json.dump() 来储存数字列表 lst = [2,3,5] filename = "numbers.json" with open(filename, 'w') as file_object: json.dump(numbers, file_object) # 储存 # 使用 json.load() 来读取 json 文件 import json filename = 'numbers.json' with open(filename) as file_object: numbers_lst = json.load(file_object) print(numbers_lst) # [2,3,5]


【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3