美文网首页
Python入门(5) 文件操作

Python入门(5) 文件操作

作者: 走码人 | 来源:发表于2022-06-15 11:49 被阅读0次

读取txt文件

导入依赖 os

import os

完整demo

import os
with open(r'd:\temp.txt', 'r', encoding='UTF-8') as file:
 lines = file.readlines()
 for line in lines:
    print(line)
file.close()

写text文件

完整demo

import os
with open(r'd:\temp.txt', 'w', encoding='UTF-8') as file:
 file.write('hello')

参考资料

https://www.runoob.com/python/file-methods.html

获取指定目录下的文件名称

def get_allfile(path):  # 获取所有文件
    all_file = []
    for f in os.listdir(path):  #listdir返回文件中所有目录
        #f_name = os.path.join(path, f)
        all_file.append(f)
    return all_file

相关文章

网友评论

      本文标题:Python入门(5) 文件操作

      本文链接:https://www.haomeiwen.com/subject/cnhxvrtx.html