ValueError:int()的基数为10的无效文字:'2 \ n3'

时间:2015-12-01 02:02:24

标签: python list

我想将下面的文本文件转换为列表:

import time
apples = 0
gold = 0

def start():
    print "Hello\n"
    print "My name is Jason\n"
    name = raw_input("What is your Name?\n")
    print "Welcome %s.\n" % name
    print "The object of this game is to pick apples and sell them for gold.\n"
    time.sleep(1)
    begin = raw_input("Would you like to play?\nY or N\n")
    if begin == "Y":
        time.sleep(1)
        beginfunction()
    if begin == "N":
        print "Okay, Please exit the terminal.\n"
        print "Goodbye!!!\n"
def beginfunction():
    global apples
    global gold
    papple = raw_input("Would you like to Pick some Apples?\nY or N\n")
    if papple == "Y":
        time.sleep(1)
        apples=apples+5
        print "Computer: You picked 5 apples.\n"
        print "You now have %s apples!!!\n" % apples
        beginfunction()
    if papple == "N":
        sell = raw_input("Would you like to sell some apples for gold?\nY or N\n")
        if sell == "Y":
            time.sleep(1)
            gold=gold+5
            apples=apples-5
            print "Computer: You sold 5 Apples for 5 Gold.\n"
            print "You now have '%s' apples, and '%s' Gold Pieces.\n" % (apples, gold)
            beginfunction()
        if sell == "N":
            print "Okay\n"
            beginfunction()

if __name__ == "__main__":
    start()

到目前为止,这是我的python代码,但我无法理解为什么它不起作用:

4,9,2
3,5,7
8,1,6

错误消息是:

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()

谢谢:)

4 个答案:

答案 0 :(得分:0)

读取正在读取整个文件(包括换行符)。所以你的实际数据如下:

songsListView

您可以使用

一次一行地阅读内容
'4,9,2\n3,5,7\n8,1,6'

或者,您可以按如下方式处理新行(“\ n”和“\ n \ r”):

d = f.readline().split(',')
while d != "":
    data = list(map(int, d))
    print(data)
    d = f.readline().split(',')

答案 1 :(得分:0)

使用solusi,您正在阅读整个文件并在逗号上拆分。由于文件由多行组成,因此它将包含换行符。 d = f.read().split(',')不会删除这些字符。

要解决此问题,请首先迭代这些行,而不是在逗号上分割整个内容:

split(',')

答案 2 :(得分:0)

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是在python

中逐行读取文件的标准方法

答案 3 :(得分:0)

您需要按换行符('\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]]