读取文件时删除空格

2024-10-02 12:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个小程序来读取逗号分隔文件(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”]]

Tags: csvthecsvfilenameinputgetastable
3条回答

Python有一个内置的csv module可以解决这些问题

以下进程将获取所需的输出:

            #Input file
            [[“Cat  , 5, 20, “meow”]% [“Dog”, 20, 20, “woof”]% [“cow”, 300, 22, “moo”]]


            #Program
            import csv
            def csv_reader1(file_obj):
                reader = csv.reader(file_obj,delimiter='%')
                for row in reader:
                    print(" ".join(row))

            if __name__ == "__main__":
                csv_path = "file3.csv"
                with open(csv_path, newline='',encoding="utf8") as f_obj:
                    csv_reader1(f_obj)

如果由于某种原因,确实无法使用csv模块,那么您当前的输出似乎已经非常接近您想要的。您只需要去掉非ASCII字符。我找到了另一个关于如何做到这一点的答案:
How can I remove non-ASCII characters but leave periods and spaces using Python?

(我也是一名新的投稿人。)

相关问题 更多 >

    热门问题