提问者:小点点

读取文件时删除空格


我做了一个小程序来读取逗号分隔文件(exel)中的内容,它可以工作,但是我得到了一些额外的字符,我需要帮助来修复它:(

def get_csv_as_table(filename, delimiter):
    csvFile=open(filename)
    for row in csvFile:
        #row=row.strip()
        row=row.split(delimiter)
        userArray.append(row)
    csvFile.close()
    return userArray
     
get_csv_as_table(userFileName, userDelimiter)`

我得到的输出是

Input the file name :- meow.csv
input the delimiter :- %
[['Cat', 'Â\xa05', 'Â\xa0Â\xa020', 'Â\xa0meow\n'], ['Dog', 'Â\xa020', 'Â\xa020', 'Â\xa0woof\n'], ['Cow', 'Â\xa0300', 'Â\xa022', 'Â\xa0moo']

我想要得到的输出是

Input the file name :- meow.csv

input the delimiter :- %

[[“Cat”, 5, 20, “meow”], [“Dog”, 20, 20, “woof”], [“cow”, 300, 22, “moo”]]

共2个答案

匿名用户

Python有一个内置的csv模块,可以解决这些问题。

匿名用户

因为您必须在没有CSV的情况下完成此操作:

def get_csv_as_table(filename, delimiter):
    csvFile=open(filename)
    for row in csvFile:
        row=row.replace("Â\xa0","").split(delimiter) #change this line
        userArray.append(row)
    csvFile.close()
    return userArray

get_csv_as_table(userFileName, userDelimiter