1

我正在尝试创建一个代码来重新格式化 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
4

1 回答 1

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:
于 2017-06-04T10:48:31.647 回答