我有文件列表,我需要检查它们是否为空 如果它们是非空的打印文件名和文件内容,则不执行任何操作
例如:file 1.html content:a,2.html content:b,3.html -empty
需要创建包含两个文件内容的结果文件:
output.txt的:
1.html
a
2.html
b
我有这段代码:
import os
files = ["1.html", "2.html", "3.html"];
for i in range(len(files)):
with open(files) as file:
first = file.read(1)
if not first:
print('') #nothing to print
else:
print file #print file name
print file.read() #print file content
得到:
with open(files) as file:
TypeError: coercing to Unicode: need string or buffer, list found
答案 0 :(得分:2)
你太复杂了,只是先加载文件内容 - 如果有的话打印出来,如果没有则忽略:
files = ["1.html", "2.html", "3.html"]
for filename in files:
with open(filename, "r") as f:
contents = f.read()
if contents:
print(filename)
print(contents)
答案 1 :(得分:1)
因为打开初始数组而不是文件[i],所以你的with语句没有用。处理此问题的更好方法是:
files = ["1.html", "2.html", "3.html"];
for f in files:
with open(f) as file:
first = file.read(1)
if not first:
print('') #nothing to print
else:
print f #print file name
print file.read() #print file content
答案 2 :(得分:1)
for file in files:
with open(file) as fin:
if fin.read():
print file
print file.read()