Python 2.7.1:如何打开、编辑和关闭 CSV 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14471049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:35:17  来源:igfitidea点击:

Python 2.7.1: How to Open, Edit and Close a CSV file

pythoncsvpython-2.7

提问by Sean

I'm having trouble opening a file (amount2.csv) making a change, saving it and closing the file.

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

How does one open a file edit, save and close it?

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

import csv

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

my error: open file 'amount2.csv', mode 'r' at 0x1004656f0 (<> removed)

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

回答by Chuck Adams

You're trying to print the file object itself, which won't do much useful. Have you looked at the documentation for the CSV module? The very first code example shows you how to use csv.reader.

您正在尝试打印文件对象本身,这没有多大用处。您是否查看过 CSV 模块的文档?第一个代码示例向您展示了如何使用 csv.reader。

回答by kalhartt

The

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

you are seeing isn't an error, but the result of your 'print f'. To instead see the contents of your file, you would do

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

To append rows to your file, instead do

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

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)

More info at Python CSV Docs

Python CSV 文档中的更多信息

EDIT:

编辑:

I misunderstood at first, you want to change all entries of '1 dozen' to '12' in your csv file. I will say first, this is easier to do without using the csv module, but here is a solution using it.

我一开始误解了,你想在你的 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)

If you're new to programming and python the most trobulesome line is probably

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

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

but this is just a list comprehension that is effectively equivalent to

但这只是一个列表理解,实际上等效于

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