Python: Can not write to CSV file - python

I have this snippet of Python code:
import csv
def analyse(csvFileToRead, csvFileToWrite):
# open file to read
openedCsvFileToRead = open(csvFileToRead)
reader = csv.reader(openedCsvFileToRead)
# open file to write
openedCsvFileToWrite = open(csvFileToWrite)
writer = csv.writer(openedCsvFileToWrite)
for row in reader:
date = row[8]
if date[0] == "5":
writer.writerow(row)
# close file
openedCsvFileToRead.close()
openedCsvFileToWrite.close()
if __name__ == "__main__":
analyse("mydata.csv", "mynewdata.csv")
when run using Python 3.4 I get the following error message:
Traceback (most recent call last):
File "main.py", line 40, in <module>
analyse("mydata.csv", "mynewdata.csv")
File "main.py", line 25, in analyse
writer.writerow(row)
io.UnsupportedOperation: not writable
What Am I doing wrong?
I'm on Windows 7 64bit.

You have to open the file in write mode:
openedCSvFileToWrite = open(csvFileToWrite, "w")
Note that in Python 2.x, the docs always use 'wb', rather than 'w'.

Related

Python reading from CSV file in python 2.7 but not python 3.6. What do i have to do to make it work in 3.6

I have some code which i coded in python 2.7, however I need it to work for 3.6 and when i run it i get this error and i am not sure why.
import csv
def ReadFromFile():
with open('File.csv', 'r') as File:
cr = csv.reader(File)
for row in cr:
Name = row[0]
Gender = row[1]
print(Name + Gender)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
ReadFromFile()
File "F:/Test.py", line 6, in ReadFromFile
Name = row[0]
IndexError: list index out of range
I am using the same code saved on a memory stick with the file in 2.7 i get my desired out come of it being read but in 3.6 i am stuck with the error. Thanks for any help
Edit: Added Print
After adding print i got
ELIZABETHFemale
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
ReadFromFile()
File "F:/Test.py", line 6, in ReadFromFile
Name = row[0]
IndexError: list index out of range
So it gave me the first line but nothing more
Python's CSV module has changed how it wants the files you pass to it to be opened. You want to avoid the file object doing any newline transformation because some CSV formats allow embedded newlines within quoted fields. The csv module will do its own newline normalization, so the usual universal newline handling the file object does is redundant.
This is mentioned in the csv.reader documentation, where it is talking about the file argument:
If csvfile is a file object, it should be opened with newline=''.
So for your code, try changing open('File.csv', 'r') to open('File.csv', 'r', newline='').
Have you tried pandas?
I think you may want to use something like
import pandas as pd
def ReadFromFile():
df = pd.read_csv('File.csv')
for row in df:
Name = row[0]
Gender = row[1]
print(Name + Gender)

Script Python using plone.api to create File appear error WrongType when set a file

Dears,
I'm creating a script python to mass upload files in Plone site, the installation is UnifiedInstaller Plone 4.3.10.
This script read a txt, and this txt have separation with semicolon, the error appear when set up a file in a new created item.
Bellow the Script.
from zope.site.hooks import setSite
from plone.namedfile.file import NamedBlobFile
from plone import api
import transaction
import csv
portal = app['Plone']
setSite(portal)
container = portal['PROCESSOS']
with open('CARGA/C008_0002.txt', 'rb') as csvfile:
reader = csv.DictReader(csvfile, delimiter=';', quotechar='|')
for row in reader:
pdf_id = 'P'+str(row['IMAGEM']).strip('Pasta Geral\\ ')
file_obj = api.content.create(
container, 'File',
title=str(row['INTERESSADO']),
id=pdf_id,
description=str(row['CNPJ / CPF'])+' '+str(row['ASSUNTO']),
safe_id=True
)
pdf_path = 'INMEQ/'+str(row['IMAGEM']).replace("\\", "/")
print(pdf_path)
file_obj.file = NamedBlobFile(
data=open(pdf_path, 'r').read(),
contentType='application/pdf',
filename=str(file_obj.id),
)
print('Created: '+row['NDOPROCESSO']+'.')
transaction.commit()
When the script will set up a file the error "WrongType" appear. See verbose bellow.
Traceback (most recent call last):
File "<console>", line 18, in <module>
File "/home/jaf/plone4310/buildout-cache/eggs/plone.namedfile-3.0.9-py2.7.egg/plone/namedfile/file.py", line 384, in __init__
self.filename = filename
File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/fieldproperty.py", line 52, in __set__
field.validate(value)
File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 182, in validate
self._validate(value)
File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 309, in _validate
super(MinMaxLen, self)._validate(value)
File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 209, in _validate
raise WrongType(value, self._type, self.__name__)
WrongType: ('processo-al-1.pdf', <type 'unicode'>, 'filename')
Thanks for you attention!
--
Juliano Araújo
You need to pass the filename as unicode.
file_obj.file = NamedBlobFile(
data=open(pdf_path, 'r').read(),
contentType='application/pdf',
filename=unicode(file_obj.id), # needs to be unicode
)
More Info in the plone.namedfile docu --> https://github.com/plone/plone.namedfile/blob/36014d67c3befacfe3a058f1d3d99a6a4352a31f/plone/namedfile/usage.rst

a bug with csv module in python

import csv
with open('database.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['NAME'])
Guys, I have a csv file with the first row as a index, and in linux the code read from row['NAME'] and print only the names form colum NAME, when I run it in windows, it says:
C:\Users\Desktop>python py.py
Traceback (most recent call last):
File "py.py", line 5, in <module>
print(row['NAME'])
KeyError: 'NAME'
WHY?
If you are using the python 2- versions, you need to open the csv with rb, i.e.:
with open('database.csv', 'rb') as csvfile:....
for reference, checkout https://docs.python.org/2/library/csv.html as it includes a part in the reader doc about this.

I/O file not getting opened

I have this csv file dl.dropboxusercontent.com/s/tb4yc3lm3gg3j22/out.csv and I am trying to replace the last column with the read method below.
In my input.csv i have to replace the last filed with some calculation. I trying as below but somehow i am getting ValueError: I/O operation on a closed file. Can you help me point out the mistake. As i am trying to open input file and write everything including the new value to out.csv file which doesnt exist initially but should be constructed on the fly.
def read():
for file in os.listdir("./"):
if file.endswith('.csv'):
fNameFull = os.path.basename(file)
inputFileName = os.path.splitext(file)[0]
with open(fNameFull, "rb") as infile, open('out.csv', "wb") as outfile:
r = csv.DictReader(infile)
w = csv.DictWriter(outfile, r.fieldnames)
w.writeheader()
for row in r:
if not row["col_last"].strip():
row["col_last"] = "calc_value"
w.writerow(row)
if __name__ == '__main__':
main()
read()
Error:
Traceback (most recent call last):
File "C:\Users\hp\Desktop\final\text\finalmod.py", line 50, in <module>
read()
File "C:\Users\hp\Desktop\final\text\finalmod.py", line 39, in read
w.writeheader()
File "C:\Python27\lib\csv.py", line 137, in writeheader
self.writerow(header)
File "C:\Python27\lib\csv.py", line 148, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
ValueError: I/O operation on closed file

Can't overwrite file on Windows

Whenever I try to overwrite a file in Python 2.7 this is what happens, code:
a = open('hello.txt')
a.write('my name is mark')
And my error is:
Traceback (most recent call last):
File "C:\Users\Mark Malkin\Desktop\New folder\opener.py", line 2, in <module>
a.write('my name is mark')
IOError: File not open for writing
From docs on open:
If mode is omitted, it defaults to 'r'.
To write instead use,
a = open('hello.txt', 'w')
Or better yet,
with open('hello.txt', 'w') as f:
f.write('my name is mark')

Categories