简体   繁体   中英

removing spaces when reading from a file

i made this small program to read whats inside a comma separated file (exel)and it works but i get few additional characters i need help to fix it:(

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

and the output i get is

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

the output i want to get is

Input the file name :- meow.csv

input the delimiter :- %

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

Python has a built in csv module that should take care of those issues.

Below process will fetch required output:

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

If you really can't use the csv module for some reason, it seems like your current output is already very close to what you want. You just need to strip away the non-ASCII characters. I found this other answer that talks about how to do that:
How can I remove non-ASCII characters but leave periods and spaces using Python?

(I am also a new contributor.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM