我正在编写用于编辑工作目录中许多文件的代码,当我运行时它会带来以下错误
Traceback (most recent call last):
File "C:Usershilary.kansiimeDocumentsSHARE FOLDER1-2JUNtest2.py", line 4
, in <module>
f1 = open(files, 'r')
TypeError: coercing to Unicode: need string or buffer, list found
下面是我写的代码
import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
f1 = open(files, 'r')
f2 = open(files+'.tmp', 'w')
for line in f1:
f2.write(line.replace('<Placemark xmlns="http://earth.google.com/kml/2.2">', '<Placemark xmlns="http://earth.google.com/kml/2.2"><car>'+files+'</car>'))
f1.close()
f2.close()
我需要你的帮助
files
是一个list
。而不是
f1 = open(files, 'r')
f2 = open(files+'.tmp', 'w')
你需要
f1 = open(f, 'r')
f2 = open(f+'.tmp', 'w')
或者只是
for f in files:
with open(f, 'r') as f1, open(f+'.tmp', 'w') as f2:
for line in f1:
f2.write(line.replace('<Placemark xmlns="http://earth.google.com/kml/2.2">', '<Placemark xmlns="http://earth.google.com/kml/2.2"><car>'+files+'</car>'))