hi guys, i'm back to learning python ! - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: hi guys, i'm back to learning python ! (/thread-30086.html) |
hi guys, i'm back to learning python ! - astral_travel - Oct-04-2020 i'm trying to take a .CSV file and write its data into another file, i don't wanna copy the file, if you'll look at my code you'll probably see what i'm trying to do... here's the code: import csv file_input = '/home/tal/code/AAPL.csv' file_output = '/home/tal/code/file_output.txt' with open(file_input, 'r') as csv_file: reader = csv.reader(csv_file) for line in reader: with open(file_output, 'w') as file_op: file_op.write(line)this is the ouput when i debug it: but i don't know how to convert the CSV data into a string...i checked allot of websites, no where to find a way... I appreciate your help Tal RE: hi guys, i'm back to learning python ! - ndc85430 - Oct-04-2020 str has a join method that will concatenate the items of an iterable (docs here), e.g.:>>> ", ".join(["foo", "bar", "baz"]) 'foo, bar, baz' RE: hi guys, i'm back to learning python ! - deanhystad - Oct-04-2020 Don't use csv if you want to read strings. You don't have to use csv to read something that is formatted as CSV. Only use csv if you want to split input lines into columns. RE: hi guys, i'm back to learning python ! - astral_travel - Oct-04-2020 thanks to both of you ! RE: hi guys, i'm back to learning python ! - perfringo - Oct-05-2020 There is some low level stuff you can let csv module to handle. For example, if there is a file with one row: "AAPL", 113.02 then we can leave handling of "" and conversion to csv module: import csv with open('aapl.csv', 'r') as f: reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC) print(*reader) # -> ['AAPL', 113.02] with open('aapl.csv', 'r') as f: data = [item for row in f for item in row.strip().split(', ')] print(data) # -> ['"AAPL"', '113.02'] RE: hi guys, i'm back to learning python ! - buran - Oct-05-2020 if you are using csv module for reading, just use it also for writing or not use csv module, just read a line, write a line or you can also look at pandas which has methods to read and write csv files RE: hi guys, i'm back to learning python ! - astral_travel - Oct-05-2020 thank you so much ! |