Sea*_*ean 16 python csv python-2.7
我无法打开文件(amount2.csv)进行更改,保存并关闭文件.
如何打开文件编辑,保存并关闭它?
import csv
changes = {
'1 dozen' : '12'
}
with open('amount2.csv', 'r') as f:
reader = csv.reader(f)
print f
f.close()
Run Code Online (Sandbox Code Playgroud)
我的错误:打开文件'amount2.csv',模式'r'在0x1004656f0(<>已删除)
kal*_*rtt 20
该
<open file 'amount2.csv', mode 'r' at 0x1004656f0>
Run Code Online (Sandbox Code Playgroud)
你看到的不是错误,而是'print f'的结果.要改为查看文件的内容,您可以这样做
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)
Run Code Online (Sandbox Code Playgroud)
要将行附加到文件中,请执行此操作
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)
Run Code Online (Sandbox Code Playgroud)
有关Python CSV Docs的更多信息
编辑:
我一开始误解,你想在你的csv文件中将'1打'的所有条目都改为'12'.我首先要说的是,如果不使用csv模块,这样做会更容易,但这是一个使用它的解决方案.
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)
Run Code Online (Sandbox Code Playgroud)
如果你是编程和python的新手,可能是最常用的
new_row = [ x.replace(key, value) for x in new_row ]
Run Code Online (Sandbox Code Playgroud)
但这只是一个列表理解,实际上相当于
temp = []
for x in new_row:
temp.append( x.replace(key, value) )
new_row = temp
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
82460 次 |
| 最近记录: |