欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > [python]非零基础上手之文件操作

[python]非零基础上手之文件操作

2025/5/5 11:29:45 来源:https://blog.csdn.net/qq_52697994/article/details/147700845  浏览:    关键词:[python]非零基础上手之文件操作

这个其实很像Node.js.

读取操作:

with open ('./xx.txt', 'r', encoding = 'utf -8') as file:
for i in file:print(i)
#"file"是个变量, 名称自定, 参数2代表'read', 表明为读取操作.

追加操作:

属于写入的一种,不会重写文档,在原有内容后添加.

with open('./xx.txt', 'a+', encoding = 'utf-8') as file:file.write('写入内容')

何为with:

是一种上下文管理器, with语句管理的代码块执行完毕时, 会自动关闭文件, 这是受推荐的方法,可以确保文件使用完毕后正确关闭. 当然,也可以调用文件对象的close()手动关闭:
可以在读取结构中安插try/finally结构,因为我们也不知道能不能读取成功:

file = open('xx.txt', 'r')
try:file_content = file.read()print(file_content)
finally:file.close()

写入操作:

重写所有内容.

with open('example.txt', 'w') as file:file.write('HelloWorld')

写入json:

需要额外模块.

import json
json_file_path = 'example.json'
data = { 'name': 'John Doe', 'age': 30 }with open(json_file_path, 'w')
json.dumps(data) # json对象转字符串

文件重命名:

import os
files = os.listdir('path-to-directory') # 获取目录中文件列表
for file in files:	full_path = os.path.join('path-to-directoro', pythonif os.path.isfile(full_path) # 检测文件是否存在new_filename = 'new_name'os.rename(full_path, os.path.join('path_to_directory', new_filename)) # 旧路径, 新路径

逐行读文件_获取全部行:

with open('file.txt', 'r') as file:lines = file.readlines()print(lines[0])

逐行读文件_获取单行:

with open('file.txt', 'r') as file:line0 = file.readline()line1 = file.readline()

创建文件:

import os
if not os.path.exists('./aa.txt'):
try:with open('./aa.txt', 'w') as file
except IOError as error:print (error)

创建目录:

import os
if not os.path.exists('./aadir'):
try:os.makedirs('./aadir')
except IOError as error:print (error)

删除文件:

import os
if os.path.isfile('./aa.txt')
try:os.remove('./aa.txt')
except OSError as error:print(error)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词