简体   繁体   English

为什么Python CSV模块在运行程序后尝试打开时将CSV文件设为只读?

[英]Why does Python CSV module make the CSV file read-only when I try to open it after running program?

I'm using a program (follows) to see the similarities in certain columns between two CSV files, then create a third when data matches certain specifications (two columns are the same but the third is not) so that I can update an e-mail list. 我正在使用一个程序(如下)来查看两个CSV文件之间某些列的相似性,然后在数据匹配某些规范时创建第三个(两列相同但第三列不相同)以便我可以更新e-邮件列表。

When I try to open the results.csv file after running the program however, Windows Excel will only open the program in read-only mode. 但是,当我在运行程序后尝试打开results.csv文件时,Windows Excel将只以只读模式打开程序。

Any thoughts? 有什么想法吗?

Here's my code: 这是我的代码:

import csv

sample_data = open("sample.csv", "r")
lib_data = open("library.csv", "r")
csv1 = csv.reader(sample_data)
csv2 = csv.reader(lib_data)

results = open("results.csv", "w")
res_csv = csv.writer(results)

limit = 1071
limit2 = 1001

x = 0
y = 0

while (y != limit):
    row1 = csv1.__next__()
    while (x != limit2):
        row2 = csv2.__next__()
        if (row1[0] == row2[3] and row1[1] == row2[2] and row1[2] != row2[5]):
            print ("SAMPLE:")
            print (row1[0], ", ", row1[1], ", ", row1[2])
            print ("LIBRARY:")
            print (row2[3], ", ", row2[2], ", ", row2[5])
            print("\n")
            res_csv.writerow(row1)
        x = x+1
    y = y+1
    x = 0
    lib_data.seek(0)

Use with to ensure files will be closed properly: 使用with确保文件将被正确关闭:

with open("sample.csv", "r") as sample_data:
    with open("library.csv", "r") as lib_data:
        with open("results.csv", "w") as results:
            # other code

You can even put several variables into one with if you're using Python >= 2.7. 你甚至可以把几个变量为一个with ,如果你使用的是Python> = 2.7。

Close the file 关闭文件

results.close() results.close()

Having the same problem when using python 2.7 and none of the solution solved my problem. 使用python 2.7时遇到同样的问题,没有一个解决方案解决了我的问题。 Solution: just add "quoting", for example: 解决方案:只需添加“引用”,例如:

res_csv=csv.writer(results,quoting=csv.QUOTE_ALL). 

This solves my problem 这解决了我的问题

You should try opening the file with specific permissions by importing os module and using file permission flags. 您应该尝试通过导入os模块和使用文件权限标志来打开具有特定权限的文件。 Here is a link to a similar post - Write file with specific permissions in Python 这是一个类似的post- Write文件的链接,该文件在Python中具有特定权限

You are leaving the files open. 您将文件保持打开状态。 To close them, note that you have to first delete the csv object that uses the open file handle! 要关闭它们,请注意您必须先删除使用打开文件句柄的csv对象! Because of this, I rarely open the file handle separately from the csv reader/writer object. 因此,我很少单独从csv reader / writer对象打开文件句柄。

So a better way to do this would be: 所以更好的方法是:

import csv

csv1 = csv.reader(open("sample.csv", "rb"))
csv2 = csv.reader(open("library.csv", "rb"))

res_csv = csv.writer(open("results.csv", "w"))

limit = 1071
limit2 = 1001

x = 0
y = 0

while (y != limit):
    row1 = csv1.__next__()
    while (x != limit2):
        row2 = csv2.__next__()
        if (row1[0] == row2[3] and row1[1] == row2[2] and row1[2] != row2[5]):
            print ("SAMPLE:")
            print (row1[0], ", ", row1[1], ", ", row1[2])
            print ("LIBRARY:")
            print (row2[3], ", ", row2[2], ", ", row2[5])
            print("\n")
            res_csv.writerow(row1)
        x = x+1
    y = y+1
    x = 0
    lib_data.seek(0)

del csv1
del csv2
del res_csv

This makes it more explicit that you have to delete the csv to close the file handle. 这使得更明确的是您必须删除csv才能关闭文件句柄。 Also note that the official csv docs state to open files in binary mode, to avoid line ending issues. 另请注意, 官方的csv docs声明以二进制模式打开文件,以避免行结束问题。

EDIT 编辑

As noted in the comments, I'm wrong about with closing the file even if the csv handle is still available. 正如评论中所指出的那样,即使csv句柄仍然可用with关闭文件我也错了。 A quick test verified this, so proper usage is: 快速测试验证了这一点,正确的用法是:

import csv

with open("sample.csv", "rb") as sample:
    csv1 = csv.reader(sample)
    with open("library.csv", "rb") as lib_data: # the csv handle for this file is never used
        with open("results.csv", "wb") as results:
            res_csv = csv.writer(results)

            limit = 1071
            limit2 = 1001

            x = 0
            y = 0

            while (y != limit):
                row1 = csv1.__next__()
                while (x != limit2):
                    row2 = csv2.__next__()
                    if (row1[0] == row2[3] and row1[1] == row2[2] and row1[2] != row2[5]):
                        print ("SAMPLE:")
                        print (row1[0], ", ", row1[1], ", ", row1[2])
                        print ("LIBRARY:")
                        print (row2[3], ", ", row2[2], ", ", row2[5])
                        print("\n")
                        res_csv.writerow(row1)
                    x = x+1
                y = y+1
                x = 0
                lib_data.seek(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM