[英]ValueError: invalid literal for int() with base 10: '2\n3'
I would like to convert my text file below into a list: 我想将下面的文本文件转换为列表:
4,9,2
3,5,7
8,1,6
Here's my python code so far, but I couldn't understand why it doesn't work: 到目前为止,这是我的python代码,但我不明白为什么它不起作用:
def main():
file = str(input("Please enter the full name of the desired file (with extension) at the prompt below: \n"))
print (parseCSV(file))
def parseCSV(file):
file_open = open(file)
#print (file_open.read())
with open(file) as f:
d = f.read().split(',')
data = list(map(int, d))
print (data)
main()
The error message is: 错误消息是:
line 12, in parseCSV
data = list(map(int, d))
ValueError: invalid literal for int() with base 10: '2\n3'
Thanks :) 谢谢 :)
Read is reading the entire file (including the newlines). Read正在读取整个文件(包括换行符)。 So your actual data looks like:
因此,您的实际数据如下所示:
'4,9,2\n3,5,7\n8,1,6'
You can either read the content in a single line at a time using 您可以一次使用以下命令一行阅读内容
d = f.readline().split(',')
while d != "":
data = list(map(int, d))
print(data)
d = f.readline().split(',')
Or, you can handle the new lines ("\\n" and or "\\n\\r") as follows: 或者,您可以按以下方式处理新行(“ \\ n”和“ \\ n \\ r”):
d = f.readline().replace("\n", ",").split(',')
With d = f.read().split(',')
, you're reading the entire file and splitting on commas. 使用
d = f.read().split(',')
,您正在读取整个文件并以逗号分割。 Since the file consists of multiple lines, it will contain newline characters. 由于文件由多行组成,因此它将包含换行符。 These characters are not removed by
split(',')
. 这些字符不会被
split(',')
删除。
To fix this, iterate over the lines first instead of splitting the whole thing on commas: 要解决此问题,请首先遍历各行,而不是将整个内容分割成逗号:
d = (item for line in f for item in line.split(','))
f.read()
will read everything including the newline character
( \\n
) and so map(int, d)
will spit out error. f.read()
将读取包括newline character
( \\n
)的所有内容,因此map(int, d)
将吐出错误。
with open(file) as f:
for line in f:
d = line.split(',')
data = list(map(int, d))
print (data)
for line in f
is a standard way to read a file line by line in python for line in f
是在python中逐行读取文件的标准方法
You need to split by newlines ( '\\n'
), in this case you should use csv
library. 您需要用换行符(
'\\n'
)分隔,在这种情况下,您应该使用csv
库。
>>> import csv
>>> with open('foo.csv') as f:
print [map(int, row) for row in csv.reader(f)]
[[4, 9, 2], [3, 5, 7], [8, 1, 6]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.