The
<open file 'amount2.csv', mode 'r' at 0x1004656f0>
widzisz nie jest to błąd, ale wynik swojego 'Print f'. Zamiast zobaczyć zawartość pliku, byś
with open('test.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
# row is a list of strings
# use string.join to put them together
print ', '.join(row)
aby dołączyć wiersze do pliku, zamiast robić
changes = [
['1 dozen','12'],
['1 banana','13'],
['1 dollar','elephant','heffalump'],
]
with open('test.csv', 'ab') as f:
writer = csv.writer(f)
writer.writerows(changes)
Więcej informacji na Python CSV Docs
EDIT:
I niezrozumiany na początku, chcesz zmienić wszystkie wpisy z "1 tuzina" na "12" w pliku csv. Powiem po pierwsze, łatwiej jest to zrobić bez użycia modułu csv, ale tutaj jest rozwiązanie z nim korzystające.
import csv
new_rows = [] # a holder for our modified rows when we make them
changes = { # a dictionary of changes to make, find 'key' substitue with 'value'
'1 dozen' : '12', # I assume both 'key' and 'value' are strings
}
with open('test.csv', 'rb') as f:
reader = csv.reader(f) # pass the file to our csv reader
for row in reader: # iterate over the rows in the file
new_row = row # at first, just copy the row
for key, value in changes.items(): # iterate over 'changes' dictionary
new_row = [ x.replace(key, value) for x in new_row ] # make the substitutions
new_rows.append(new_row) # add the modified rows
with open('test.csv', 'wb') as f:
# Overwrite the old file with the modified rows
writer = csv.writer(f)
writer.writerows(new_rows)
Jeśli jesteś nowy w programowaniu i pytona najbardziej trobulesome linia jest prawdopodobnie
new_row = [ x.replace(key, value) for x in new_row ]
ale jest to po prostu lista zrozumienie, że jest skuteczny odpowiednik
temp = []
for x in new_row:
temp.append(x.replace(key, value))
new_row = temp
To nie może być przyczyną błędu, ale proszę zobaczyć, że otworzysz z flagą b, tj. "rb" zamiast r. Dokumenty dla csv.reader mówią: "Jeśli csvfile jest obiektem pliku, musi być otwarty z flagą" b "na platformach, na których to robi różnicę." Powszechnie wiadomo, że ma to wpływ na system Windows. –