Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

csv

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.

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.

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)
like image 354
James Roseman Avatar asked Jul 12 '26 10:07

James Roseman


1 Answers

Use with to ensure files will be closed properly:

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.

like image 70
Jan Pöschko Avatar answered Jul 14 '26 01:07

Jan Pöschko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!