Python 使用循环写入目录中的每个文件
使用下面的代码,我制作了一个htmlfiles.txt,其中包含目录中的HTML文件名: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() 在第二阶段,我希望
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])