简体   繁体   English

使用 Python 写入目录中的所有 *.txt 文件

[英]Write in all the *.txt files within a directory using Python

I want to write in all the files within a directory based on their extensions.我想根据扩展名写入目录中的所有文件。 I can write to a specific file but my goal is code that can write to all the *.txt files that are in a specific directory.我可以写入特定文件,但我的目标是可以写入特定目录中所有*.txt文件的代码。 With the following code I can list all text files and search for a file but as a beginner in Python I don't know how to write a sentence in all the *.txt files.使用以下代码,我可以列出所有文本文件并搜索文件,但作为 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"))

In your example you should be able to just do the following:在您的示例中,您应该能够执行以下操作:

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.

To do all of them:要做到所有这些:

for textfile in os.listdir():
    if textfile.endswith(".txt"):
        with open(textfile, "a") as f:
            f.write("a")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用python从目录中的所有.txt文件中获取行 - Get rows from all .txt files in directory using python 如何找到一个目录下的.txt文件,并写入python中? - how to find .txt files in a directory, and write in it in python? 在 Python 中查找扩展名为 .txt 的目录中的所有文件 - Find all files in a directory with extension .txt in Python Python:将目录中的所有文件转换为一个 .TXT? - Python: Convert all files in directory into one .TXT? 使用python程序重命名linux目录中的所有XML文件 - Using a python program to rename all XML files within a linux directory 如何使用python使用带有for循环的目录中的所有txt文件 - How do I use all the txt files from a directory with a for loop using python 使用过滤器和地图在目录中找到扩展名为.txt和.py的所有文件(使用python) - Find all files in directory with extension .txt and .py with python using filter and map 如何识别 Python 中的目录和子目录中的 all.txt 文件? - How do I identify all .txt files in a directory and subdirectories in Python? 使用 Python 通常在目录中计算文件 - Counting files normally within a directory using Python 错误:没有这样的文件或目录。 无法在 python 的 for 循环中写入文件 - Error: No such file or directory. Unable to write files within for loop in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM