中的代码执行不一致复制(这可以正常工作,大概是因为Python中的bug已经修复/更新)和IDLE,在IDLE中代码不能正常工作。你知道吗
我查阅了文档,并在以前的堆栈溢出答案中添加了“换行符”,但问题仍然存在。你知道吗
您会注意到repl it,这里:(非常适合)
但是,在空闲状态下,粘贴文件内容(没有换行符)可以正常工作
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中工作得非常好
但空闲时出现此错误
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']
>>>
对于学生来说,这是一个巨大的问题,他们需要能够在两者之间保持一致性复制而空闲就是他们在学校和家庭环境之间工作的地方。你知道吗
任何一个答案,显示代码,使它可以工作在这两个是我要找的。你知道吗
尝试使用编解码器,并明确指定文件的编码为UTF-8。你知道吗
最简单的答案如下:
但您的原始代码应该可以工作-我已经运行了它,但在linux而不是windows上。如果我能请你做更多的工作:
这将产生一个
,
列表,但中间有13,10
或10
,甚至可能有10,13,10
之类的内容。这些是我们讨论过的\r\n
和\n
,但我想知道你是否设法得到了第三个选项? 如果是这样的话,我想你需要重写这个文本文件来获得正常的行尾。你知道吗--(根据评论更新)
关于
10,13,10
,我唯一的建议就是只在一个应用程序(比如记事本)中编辑文本文件,而不要在另一个应用程序中编辑它。你知道吗实际的问题来自于在两个应用程序中编辑文件,每个应用程序对行尾应该是什么有不同的解释(windows应用程序应该是
\r\n
)复制是\n
。我以前遇到过,但从来没有制定出行动的顺序。你知道吗使用过滤器可能有助于:
相关问题 更多 >
编程相关推荐