向多个(txt)文件添加内容python

2024-06-16 12:13:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要超过2000虚拟(txt)文件voor测试回收站功能。我用以下代码创建了txt虚拟文件:

list = range(0,2000)
vulling = list

with open("path/file.txt", "w") as f:
for s in vulling:
    f.write(str(s) +"\n")

List = open("path/file.txt")
List2 = (s.strip() + ' dummy' for s in List)
for item in List2: 
    open('path/%s.txt'%(item,), 'w')

但是,由于我不能上传空文件,我需要在这些文件中添加内容。所有这些文件的内容都可以相同。例如:在每个文件中添加一个字符串“Spam”。对此,最好的解决方案是什么?在


Tags: 文件pathintxt内容foropenitem
1条回答
网友
1楼 · 发布于 2024-06-16 12:13:48

最简单的方法是创建包含您想要开始的内容的文件:

import os.path


def create_test_files(target_dir, content, n=2000, template="file_%s.txt"):
    for i in xrange(n):
        path = os.path.join(target_dir, template % i)
        with open(path, 'w') as fh:
            fh.write(content)

        yield path


for file_name in create_test_files("/tmp/example", 'Spam'):
    print file_name

这是为您选择文件名,因此如果您需要特定的文件名,您必须更改它。在

这真的很快。另一种方法(创建然后复制)将导致必须读取原始文件2000次。既然我们已经知道我们想要的内容,我们可以节省时间。在

注意:此解决方案使用生成器,因此除非您强制它迭代(例如,通过将其放入循环或元组中),否则它不会生成任何文件。在

相关问题 更多 >