I am trying to open a CSV file on Anaconda (Python 3) unsuccessfully.
I tried with a raw string, I included the whole path and also tried with the double backslashes but nothing worked. I still get the Errno 2 No such file or directory.
This is my code:
reader = csv.reader(open(r'C:\Users\Marco\Desktop\trainingset.csv', newline=''), delimiter=' ', quotechar='|')
for row in reader:
print(", ",join(row))
I have the same issue when trying to open a csv file this way... I don't know the reason but instead, I use the pandas library that has a method named read_csv()
pandas.read_csv('myfile.csv')
It gets the content of your csv file as a dataframe object. This works with Python 3.5 using Anaconda3.
Related
I just started learning Python this month with no prior coding knowledge. Before I could even get to practice coding, I was stuck with opening & importing files! To this end, I have no idea how to fix the problems as a newbie, so I will try to explain as best as I can.
1. Opening files.
Working directory is correct. The csv file was created with Geany on the Ubuntu operating system.
name=[]
age=[]
height=[]
with open(’/home/stephanie/chapter5exercise.csv’, encoding=’utf-8’,mode=’r’,newline=’’) as
csv file:
reader = csv.reader(csvfile, delimiter=’,’)
for row in reader:
name.append(row[0])
age.append(row[1])
height.append(row[2])
print("Done!")
**Error message:**
File "<ipython-input-3-f801fef0d65e>", line 5
with open(’/home/stephanie/chapter5exercise.csv’, encoding=’utf-8’,mode=’r’,newline=’’) as
^
SyntaxError: invalid character in identifier
2. Importing files
I downloaded a whatsapp chat text file for a coding exercise. It is stored in my Desktop environment. However, when I attempted to import it on Jupyter Notbook it didn't work.
I believe this is the problem, although I do not know how to work-around this:
the txt file's location as shown in my terminal:
/Users/Mac/Desktop
while the working directory as shown on Jupyter is:
/home/stephanie/Desktop
with open ("_chat.txt") as f:
data = f.readlines()
**error message:**
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-5-07cb5c381c47> in <module>
----> 1 with open ("_chat.txt") as f:
2 data = f.readlines()
FileNotFoundError: [Errno 2] No such file or directory: '_chat.txt'```
Any input or advice is greatly appreciated. Thanks very much in advance!
For the first error, try changing the apostrophes in the open line. For example, change ’/home/stephanie/chapter5exercise.csv’ to '/home/stephanie/chapter5exercise.csv'.
Apparently, the apostrophe (’) that you are using is not the correct one.
For the second error, try giving the entire path of the txt file.
I have python 2.7 code with creates a builtin file object which return me a file object <type 'file'>
file(os.path.join('/tmp/test/', 'config.ini'))
Same code i changed in python 3.7 as below it returns <class '_io.TextIOWrapper'>
open(os.path.join('/tmp/test/', 'config.ini'))
How can i get a file object type in python 3
You can use them the exact same way.
file = open(os.path.join("/tmp/test/", "config.ini"))
print(file.read()) # Will print file contents
Or use pathlib:
from pathlib import Path
file = Path("/tmp/test") / "config.ini"
print(file.read_text()) # will do the same
You're not looking for a file object. You're looking for an object that'll let you read and write files.
I need to transform the tables from a website to a CSV file.
I am using Python 3 from a raspberryPi.
Here is the code that I am using:
from urllib.request import urlopen, Request, URLError
from TableParser import TableParser
url_addr ='http://www.tbs-sct.gc.ca/pses-saff/2017-2/results-resultats/bq-pq/12/org-eng.aspx#s1'
req = Request(url_addr)
url = urlopen(req)
tp = TableParser()
tp.feed(url.read())
#Here I want the first table
my_table = tp.get_tables()[0]
filename = 'table_as_csv.csv'
f = open(filename, 'wb')
with f:
writer = csv.writer(f)
for row in table:
writer.writerow(row)
When I try to run it, I get:
ImportError: No module named 'TableParser'.
I am new to Python and I don't know what to do. Any help would be very appreciated.
Thanks!
First off, I think you should familiarise yourself with python and its syntax as well as how it handles errors. Clearly you want to do something quick and be done with it. Here's a simple python tutorial
To answer your question
ImportError exceptions occur when you do not have that particular module installed using pip installation preferrably. Until it is installed your script wont run successfully.
The error means TableParser has not been installed yet and you could do this by
pip3 install TableParser
This assumes you know where the module is and can be installed using pip
I see you are using the module csv but have not imported it as well. You should.
The following code works fine to display a pdf file with python 3.2. However with python 3.6 it doesn't (the browser gives a 'Failed to load PDF document' error). I think this is because the byte string returned by read() in 3.6 prints with a leading b' and trailing '.
Can anyone tell me how to do this in 3.6? Thank you.
#!/usr/bin/python
with open('sol.pdf', 'rb') as fp:
print("Content-type: application/pdf\n")
print(fp.read())
The following should work:
with open('sol.pdf', 'rb') as fp:
print("Content-type: application/pdf\n")
sys.stdout.flush()
sys.stdout.buffer.write(fp.read())
The sys.stdout.flush needs to appear before the sys.stdout.buffer.write to ensure that the headers appear first.
my folder structure is :
datasets/file.csv
source/code.ipynb
from within i want to access the file named file.csv.
import pandas as pd
data = pd.read_csv("../datasets/file.csv")
This is giving me the error : ParserError: Error tokenizing data. C error: Expected 1 fields in line 68, saw 2
How to access file using relative path in pandas python?
I am using Python3.6 with Anaconda in Windows 8.1 with Jupyter notebook.
The ParseError indicates that your error is in parsing the file, not locating and opening it. To verify this, try:
test_file = open('../datasets/file.csv')
for line in test_file:
print(line.strip())
This should print out the lines in file.csv.