python - 使用 Python 写入目录中的所有 *.txt 文件
问题描述
我想根据扩展名写入目录中的所有文件。我可以写入特定文件,但我的目标是可以写入*.txt
特定目录中所有文件的代码。使用以下代码,我可以列出所有文本文件并搜索文件,但作为 Python 的初学者,我不知道如何在所有*.txt
文件中写一个句子。
import glob
import os
directory=os.listdir(r'C:\Users\Lenovo\Desktop\z')
myfiles=glob.glob('*.txt')
print(myfiles)
def find_files(filename, search_path):
result= []
for root, dir, files in os.walk(search_path):
if filename in files:
result.append(os.path.join(root, filename))
return result
print(find_files("zineb.txt",r"C:\Users\Lenovo\Desktop\z"))
解决方案
在您的示例中,您应该能够执行以下操作:
textfiles = find_files("zineb.txt",r"C:\Users\Lenovo\Desktop\z")
for textfile in textfiles: # go over each file that it found
with open(textfile, "a") as f: # open the textfile in mode append (hence the a) and have it be assigned to f
f.write("a") # then write "a" to the file.
要做到所有这些:
for textfile in os.listdir():
if textfile.endswith(".txt"):
with open(textfile, "a") as f:
f.write("a")
推荐阅读
- android - 谷歌地图上不显示地图路径?
- reactjs - 从表单发送电子邮件附件
- swift - 如何约束协议类型的参数以符合 Swift 4 中的 AnyObject?
- networking - 为什么我无法 ping 到本地网络中的另一台设备
- php - 如何从 codeigniter 调用 oracle 存储过程
- c++ - EnumWindows 不检测窗口
- typescript - Typescript接口方法重载不起作用
- android - Kotlin 最佳实践:声明/初始化实例变量
- reactjs - 更新用户名后不重新呈现个人资料页面
- coq - Coq:在假设或目标中使用“forall”重写