Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用循环写入目录中的每个文件_Python_For Loop - Fatal编程技术网

Python 使用循环写入目录中的每个文件

Python 使用循环写入目录中的每个文件,python,for-loop,Python,For Loop,使用下面的代码,我制作了一个htmlfiles.txt,其中包含目录中的HTML文件名: import os entries = os.listdir('/home/stupidroot/Documents/html.files.test') count=0 for line in entries: count += 1 f = open("htmlfiles.txt", "a") f.write(line + "\n") f.close() 在第二阶段,我希望

使用下面的代码,我制作了一个htmlfiles.txt,其中包含目录中的HTML文件名:

import os
entries = os.listdir('/home/stupidroot/Documents/html.files.test')
count=0
for line in entries:
    count += 1
    f = open("htmlfiles.txt", "a")
    f.write(line + "\n")
    f.close()
在第二阶段,我希望对每个文件进行如下修改:

lines = open('filename.html').readlines()
open('filename.html', 'w').writelines(lines[20:-20])
此代码删除HTML文件中的第一行和最后20行


我只想使用for循环简化所有文件。

您只需打开
htmlfiles.txt
文件,从每行读取每个文件名,然后执行以下操作:

with open("htmlfiles.txt") as fic:
    for filename in fic:
        filename = filename.rstrip()
        lines = open(filename).readlines()
        open(filename, 'w').writelines(lines[20:-20])