How to use DictReader in csv package? - python

I try to import my CA-10-60 file with this code:
import csv
with open('CA-10-60.csv', newline='') as f:
reader = csv.DictReader(f, delimiter='')
for row in reader:
print(row['Contract'], row['Serial'])
But I get this Error:
Traceback (most recent call last):
File "C:/Users/id984876/PycharmProjects/Search Engine SMC/flask/play.py", line 3, in <module>
reader = csv.DictReader(f, delimiter='')
AttributeError: module 'csv' has no attribute 'DictReader'

One issue you will definitely have is your delimiter needs to be a one character string as evidenced by what happens when I try and replicate your error -
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\caleb\AppData\Local\Programs\Python\Python36\lib\csv.py", line 87, in __init__
self.reader = reader(f, dialect, *args, **kwds)
TypeError: "delimiter" must be a 1-character string
Try fixing that and see if anything changes. As far as I can tell, the csv module is present in both 2.7.14 and 3.6.3 so unless you are running an older version I can't imagine any issues with the import.

Related

TypeError when reading CBOR file

I am working on a project using the CBOR file to contain data. I already install cbor with pip install cbor. But I cannot read it.
This is my code:
import cbor
cbor.loads(r"C:\Users\User\Desktop\project\score.cbor")
Then its return this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\User\Anaconda3\envs\pyenv\lib\site-packages\cbor\cbor.py", line 263, in loads
fp = StringIO(data)
TypeError: a bytes-like object is required, not 'str'
How to solve this problem? And is there a way to convert CBOR to JSON file because I find it easier to work with the JSON file in Python.
I still don't know how to solve this problem with cbor, I use cbor2 instead and it works.
import cbor2
path = "home/data/score.cbor"
with open(path, 'rb') as fp:
obj = cbor2.load(fp)
print(obj)
Output
{'root': {'probe': 20, 'candidate': 31}, 'tree': [], 'support': []}

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)

Importing a file based upon the path

I have a python script that exports a file using the following command in a function. It's works, but I need to import that file after exporting and loop through it.
connector.save_csv(path,'_'+"GT_Weekly"+'_'+keys)
Thereore, I've been hard coding the file name and using it with open(). However, I was wondering how I could specify the file name in the same way as specified when I saved it.
Here's the hard coded approach:
with open(path,'_'+"GT_Weekly"+'_'+keys+'.csv', 'rt') as csvfile:
csvReader = csv.reader(csvfile)
data = []
I want to take the save_csv arguments and add it to open but that doesn't work. How can I do this
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
Both keys and path were specified as
keys ="football"
path = "/home/abraham/Trends"
What component needs to be changed to an integer? It's not evident to me
Furthermore, when I add int,I get the following error
with int(open(path,'_'+"GT_Weekly"+'_'+keys+'.csv', 'rt')) as csvfile:
csvReader = csv.reader(csvfile)
data = []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>>
You seem to think open accepts a path, a file name, and a mode; but it doesn't. The parameters are a file name, a mode, and a buffer size. The buffer size should be an integer, but you are passing 'rt'; hence, you get an error message.
I guess you want open(os.path.join(path, filename), 'rt') instead, or possibly open(path + filename, 'rt'), if the last component of path is a prefix part of the filename you want, not a directory name.

Issue with csv module in Python

I'm having an issue using Python's csv module. I created a simple file in Excel containing two columns (names and ages of people) and saved it as a csv file. I then ran the following lines in Python:
import csv
csv_rader = csv.DictReader(open('people.csv'))
people = list(csv_reader)
and I got the following error:
Traceback (most recent call last):
File "", line 1, in
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 107, in next
self.fieldnames
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 90, in fieldnames
self._fieldnames = self.reader.next()
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
Does anyone know what could be causing this, and how to go about fixing it?

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