【发布时间】:2017-07-21 05:41:59
【问题描述】:
repl.it(工作正常,可能是因为 Python 中的错误已得到修复/更新)和 IDLE 中的代码执行存在差异,其中代码无法正常工作。
我已经查阅了文档,以及之前的堆栈溢出答案以添加“换行符”,但问题仍然存在。
你会注意到它的复制,在这里:(完美运行)
但是,在 IDLE 中粘贴文件内容时(没有换行符)可以正常工作
001,Joe,Bloggs,Test1:99,Test2:100,Test3:1002,Ash,Smith,Test1:20,Test2:20,Test3:100003003,Jonathan,Peter,Test1:99,Test2:33,Test3:44
但是在将文件内容粘贴到 txt 文件中时(每条记录都在一个新行上),如下所示:
001,Joe,Bloggs,Test1:99,Test2:100,Test3:1
002,Ash,Smith,Test1:20,Test2:20,Test3:100003
003,Jonathan,Peter,Test1:99,Test2:33,Test3:44
输出错误如下(每行后产生一个新列表):
[['001', 'Joe', 'Bloggs', 'Test1:99', 'Test2:100', 'Test3:1'], [], ['002', 'Ash', 'Smith', 'Test1:20', 'Test2:20', 'Test3:100'], ['003'], ['', 'Jonathan', 'Peter', 'Test1:99', 'Test2:33', 'Test3:44']]
代码在这里:
import csv
#==========1. Open the File, Read it into a list, and Print Contents
print("1==============Open File, Read into List, Print Contents")
#open the file, read it into a list (each line is a list within a list, and the end of line spaces are stripped as well as the individual elements split at the comma)
with open("studentinfo.txt","rb",newline="") as f:
studentlist=list(csv.reader(f))
print(studentlist)
我已经尝试过,正如文档和 stackoverflow 上的先前答案所建议的那样,添加:(换行符)
with open("studentinfo.txt","r",newline="") as f:
很遗憾,错误仍然存在。
任何带有解释的建议/解决方案将不胜感激。
更新,我也试过这个:
with open("studentinfo.txt",newline="") as f:
reader=csv.reader(f)
for row in reader:
print(row)
再次,它在 replit 中完美运行
但在 IDLE 中出现此错误
1==============Open File, Read into List, Print Contents
['001', 'Joe', 'Bloggs', 'Test1:99', 'Test2:100', 'Test3:1']
[]
['002', 'Ash', 'Smith', 'Test1:20', 'Test2:20', 'Test3:100']
['003']
['', 'Jonathan', 'Peter', 'Test1:99', 'Test2:33', 'Test3:44']
>>>
对于需要能够在 repl.it 和 IDLE 之间保持一致性的学生来说,这是一个巨大的问题,这是他们在学校和家庭环境之间所做的工作。
任何显示代码允许它在两者上工作的答案都是我所追求的。
【问题讨论】:
-
有人吗?有人吗?
-
您需要显示“原样”文件的实际字节数。我相信
csv模块解析的 CSV 格式需要 CRLF 行结尾,无论平台如何。 -
您能否发布一个解决方案 - 我不知道这意味着什么!谢谢
-
@pythoncarrot:那条评论是针对我的吗?我的“解决方案”是问题中的代码实际上是正确的。相反,文件中的字节是错误的。 (或者至少对于
excel方言是错误的,这是csv模块的默认设置。) -
谢谢 - 你能进一步解释一下吗?如果是文件中的字节错误,这是什么意思,如何纠正?