我正在尝试创建一个代码来重新格式化csv文件并在csv文件上写一个列表列表。代码不是很干净,但过去一直有效。但是现在我添加了一个新的第一部分,在那里我删除行并创建文件之间,它给了我一个类型错误。感谢你的帮助,我无法意识到我做错了什么。
import os
import csv
outputfile = input("")
nodefile = input("")
inputfile =input("")
betweenfile= input("")
os.mknod(outputfile)
os.mknod(nodefile)
os.mknod(betweenfile)
with open(inputfile, newline='') as data:
reader = csv.reader(data, delimiter=',')
stack=[]
try:
for row in reader:
del row[0]
del row[3]
del row[3]
del row[3]
del row[3]
del row[3]
del row[4]
row[1],row[2]=row[2],row[1]
row[2],row[3]=row[3],row[2]
stack.append(row)
except:
IndexError
with open(betweenfile, 'w') as outputfile:
writer= csv.writer(outputfile, delimiter=',')
for row in stack:
writer.writerow(row)
with open(betweenfile, newline='') as data:
reader = csv.reader(data, delimiter=',')
listee=[]
for row in reader:
if row[3]=='1':
row[0],row[1]=row[1],row[0]
if row[3]=='3':
row[0],row[1]=row[1],row[0]
row.pop(3)
listee.append(row)
listee.pop(0)
for row in listee:
for i in range(len(row)):
if row[i]== '0':
listee.remove(row)
for row in listee:
for i in range(len(row)):
if row[i]== '0':
listee.remove(row)
print(type(listee))
with open(outputfile, 'w') as outputfile:
writer= csv.writer(outputfile, delimiter=',')
writer.writerow(['from', 'to' , 'weight'])
for row in listee:
writer.writerow(row)
错误消息是:
Traceback (most recent call last):
File "dataformater3.py", line 54, in <module>
with open(outputfile, 'w') as outputfile:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
答案 0 :(得分:1)
这就是你永远不应该重用变量的原因。他们有意想不到的副作用。首先,将outputfile
定义为
outputfile = input("")
然后
with open(betweenfile, 'w') as outputfile:
outputfile
现在是一个文件句柄,它不再是用户输入的字符串。而且还在代码的下方。
print(type(listee))
with open(outputfile, 'w') as outputfile:
您正在传递文件句柄作为要打开的第一个参数,这显然不知道如何处理它。
然后,补救措施是避免重复使用变量。为什么不借用.NET
开发者进行以下更改
outputfile_s = input("")
....
with open(outputfile_s, 'w') as outputfile_f: