Python Forum

Full Version: hi guys, i'm back to learning python !
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:

Output:
Traceback (most recent call last): File "/home/tal/.config/JetBrains/PyCharmCE2020.2/scratches/scratch.py", line 12, in <module> file_op.write(line) TypeError: write() argument must be str, not list
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
str has a join method that will concatenate the items of an iterable (docs here), e.g.:

>>> ", ".join(["foo", "bar", "baz"])
'foo, bar, baz'
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.
thanks to both of you !
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']
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
thank you so much !