NUB at codes
NUB at codes

Reputation: 59

Overwriting data list: take a file and its list and write that list to a CSV file

i want to take a fine name and its list and replace that into another CSV file, or replacing the csv file with itself, overwriting it with the same content.
the function comand should be save_friends('data.csv', load_friends('data.csv'))

def save_friends(friend_info, new_list):
    with open(friend_info, 'w') as f:
        for line in new_list:
            f.write(line + '\n')

with this function i get this error TypeError: can only concatenate tuple (not "str") to tuple

so I added v.append(tuple(line)) above f.write(line + '\n'), and it basically overwrite the file with empty data. How do I get this function working?

Upvotes: 0

Views: 148

Answers (1)

mgilson
mgilson

Reputation: 310227

It appears to me that new_list is an iterable containing tuple objects. As such, you can't concatenate it with a str:

>>> ("foo","bar") + "\n"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "str") to tuple

The typical approach is to str.join the tuple into a str before you try to concatenate it with the "\n". e.g.:

>>> ','.join(("foo","bar")) + "\n"
'foo,bar\n'

So applying that to your code leaves us with:

def save_friends(friend_info, new_list):
    with open(friend_info, 'w') as f:
        for line in new_list:
            f.write(','.join(line) + '\n')

Depending on what the elements of line are, you might need to go a step further to make sure that each element in the tuple is also a str:

f.write(','.join(str(x) for x in line) + '\n')

because if join encounters elements which aren't strings, it complains:

>>> ','.join((1,2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found

Upvotes: 1

Related Questions