gpt4 book ai didi

Python 2.7.1 : How to Open, 编辑并关闭 CSV 文件

转载 作者:太空狗 更新时间:2023-10-29 16:55:19 24 4
gpt4 key购买 nike

我在打开文件 (amount2.csv) 进行更改、保存并关闭文件时遇到问题。

如何打开一个文件编辑、保存和关闭它?

import csv

changes = {
'1 dozen' : '12'
}
with open('amount2.csv', 'r') as f:
reader = csv.reader(f)
print f
f.close()

我的错误:打开文件“amount2.csv”,模式“r”位于 0x1004656f0(<> 已删除)

最佳答案

<open file 'amount2.csv', mode 'r' at 0x1004656f0>

您看到的不是错误,而是“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)

要将行附加到您的文件,请执行

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)

更多信息请访问 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)

如果您不熟悉编程和 python,最麻烦的行可能是

new_row = [ x.replace(key, value) for x in new_row ]

但这只是一个有效等价于

的列表理解
temp = []
for x in new_row:
temp.append( x.replace(key, value) )
new_row = temp

关于Python 2.7.1 : How to Open, 编辑并关闭 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14471049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com