'Python Error io.UnsupportedOperation: not readable
i have this error and i don't know why i got it. I followed the steps from my Python manual and i got this. I am tryng to cleanup the file on column 8 and 9 if they have that odd character. If someone could help me, please advise.
The error appear on the line of code: for row in csv.reader(f):
Please find below my code:
import csv
file = '/Users/cohen/Desktop/sdn-2.csv'
newstring = "null"
newinteger = int(0)
with open(file, 'r+') as f:
for row in csv.reader(f):
if row[7] =="-0-":
row[7] = newinteger
if row[8] == "-0-":
row[8] = newinteger
f.close()
***LATER EDIT I changed the code as above, but is not doing anything is not replacing the -0-
with 0
Solution 1:[1]
EDIT:
You need to open the file with r+. Using w is for write only, r+ is for both write and read access.
with open(file, 'r+') as f:
Using == as in row[7] == newinteger is calling the equality operator. It checks if the left and right operand's values are the same. You want to be setting the new value with =.
row[7] = newinteger
Solution 2:[2]
The other stuff that those before me said too but I think this error is from the parentheses around the string "-0-"
. And maybe the space on the first use as well.
if row[7] ==("-0-"):
should be: if row[7] == "-0-":
if row[8] == ("-0-"):
should be: if row[8] == "-0-":
Solution 3:[3]
This was my solution: to create an output file and to write in it, what i read from the source file. Is a bit odd, as in VBA was even easier to do this, then in python, but this is the solution within the csv module from pythn. I dont like that i have to create another file, and i can't basicaly write inside the readed file, and i have to write into a brand new file, but this is life....If someone has a better approach, I am opened to new.
Hope that others will use this code.
import csv
newstring = "null"
newinteger = (0)
with open('/Users/cohen/Desktop/sdn-4 2.csv', 'r') as file1, open('/Users/cohen/Desktop/new_sdn.csv', 'w', newline='') as file2:
reader = csv.reader(file1, delimiter=',')
writer = csv.writer(file2, delimiter=',')
for row in reader:
replaced1 = row[7].replace('-0-', newstring)
row[7]=replaced1
replaced2 = row[8].replace('-0-', newinteger)
row[8]=replaced2
writer.writerow(row)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jdhurricanes |
Solution 2 | Tyler Christian |
Solution 3 | Cohen |