天道酬勤,学无止境

Unable to read csv file by Anaconda IDE

Question

My Anaconda IDE is unable to read csv file using panda.read_csv() function.

File name is baseball which is kept at location C:\Users\Firdaus\Desktop

I have written following code:

# Import pandas as pd
import pandas as pd
# Import the cars.csv data as Base
Base = pd.read_csv('C:\Users\Firdaus\Desktop\baseball.csv')
# Print out Base
print(Base)

Error is:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Answer1

In regular python strings, the \U character combination signals an extended Unicode codepoint escape. You can use one of the following:

r'C:\Users\Firdaus\Desktop\baseball.csv' #r stands for raw strings
'C:\\Users\\Firdaus\\Desktop\\baseball.csv' #using double slashes
'C:/Users/Firdaus/Desktop/baseball.csv' #using forward slashes

Hope this helps.

标签

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐
  • unable to load “gcs.csv” file in gdal
    Question This question might be repeat but I did not get answer. I have write flowing code in python ide . out_srs = osr.SpatialReference() **self.out_srs.ImportFromEPSG(4326)** It run fine but when i run it from application it cause an error as follows Note - Error in line enclosed in 2 stars ----- "Unable to load EPSG support gcs.csv file check setting GDAL_DATA environment variable which point to gdal library contains EPSG.csv file" I have done it but i still get this error. but this code run separately but not in application. This code is from gdal2tile module of gdal. i am using python 2
  • Unable to use seaborn.countplot
    Question I'm trying to plot some graphs using the latest version of Pycharm as a Python IDE. As an interpreter, I'm using Anaconda with Python 3.4.3-0. I have installed using conda install the news version of pandas (0.17.0), seaborn (0.6.0), numpy (1.10.1), matplotlib (1.4.3), ipython (4.0.1) Inside the nesarc_pds.csv I have this: IDNUM,S1Q2I 39191,1 39787,1 40082,1 40189,1 40226,1 40637,1 41306,1 41627,1 41710,1 42113,1 42120,1 42720,1 42909,1 43092,1 7,2 15,2 25,2 40,2 46,2 49,2 57,2 63,2 68,2 100,2 104,2 116,2 125,2 136,2 137,2 145,2 168,2 3787,9 6554,9 7616,9 11686,9 12431,9 14889,9 17694
  • “CSV file does not exist” for a filename with embedded quotes
    Question I am currently learning Pandas for data analysis and having some issues reading a csv file in Atom editor. When I am running the following code: import pandas as pd df = pd.read_csv("FBI-CRIME11.csv") print(df.head()) I get an error message, which ends with OSError: File b'FBI-CRIME11.csv' does not exist Here is the directory to the file: /Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv". When i try to run it this way: df = pd.read_csv(Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv") I get another error: NameError: name 'Users' is not defined I have also put this
  • Pandas Dataframe - RemoteDataError - Python
    Question I'm trying to pull data from yahoo finance. Here is the error I'm getting: File "banana.py", line 35, in <module> data = web.DataReader(ticker, "yahoo", datetime(2011,1,1), datetime(2015,12,31)) File "C:\Users\ll\Anaconda2\lib\site-packages\pandas_datareader\data.py", line 94, in DataReader session=session).read() File "C:\Users\ll\Anaconda2\lib\site-packages\pandas_datareader\yahoo\daily.py", line 77, in read df = super(YahooDailyReader, self).read() File "C:\Users\ll\Anaconda2\lib\site-packages\pandas_datareader\base.py", line 173, in read df = self._read_one_data(self.url, params
  • Pylint does not work in visual studio code
    Question I use Visual Studio code as python IDE on Mac, and everything works fine for me. But a couple of weeks ago I've started to use Windows. And suddenly I'm unable to use pylint in the project I've started on Mac. I have explicitly activated pylintEnabled option (=True) full path to pylint.exe is set ("c:\Anaconda 3...") pylintrc file with initial hook adding project to pythonpath (generated by pylint using --generate-rcfile) in the root directory. With the very same parameters, everything works fine both on Linux (Ubuntu 16.10) and Mac. And does not work on two Windows machines. It seems
  • Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings'
    Question I am trying to make simple python program that is opening list of webpages for a user to manually download reports from the site. I don't have any previous experience with preparing exe files.. And I'm just in learning process for python coding. All of this is done on Windows 7 x64 This is my python code: #!C:/Python34/python.exe -u from splinter import * import time import os import csv #---------------------------------- raporty = [] with open('../raporty.csv', newline='') as csvfile: contents = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in contents: r = ', '.join(row
  • Unable to Include Jinja2 Template to Pyinstaller Distribution
    Question I have a python script that uses Jinja2 template, and I'm trying to create a one-folder distribution using Pyinstaller. In Jinja, I'm letting the program understand the location of the templates by using a PackageLoader class. The code below shows that it's pointing to my templates folder under pycorr Python package. env = Environment(loader=PackageLoader('pycorr', 'templates')) template = env.get_template('child_template.html') And here's what my folder structure looks like: pycorr | | | + templates | | | + base.html | + child.html When I compile the package into a single folder
  • Rodeo UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
    Question I have just started using Python3. I am trying to open a csv file using Rodeo IDE fp = open('Proteomics_Data.csv') # open file on read mode lines = fp.read().split("\n") # create a list containing all lines I am getting an error I paste it below. UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) <ipython-input-347-aebf19dd596a> in <module>() ----> 1 lines = fp.read().split("\n") /Users/alessandro/anaconda/lib
  • ValueError: array must not contain infs or NaNs during Biclustering
    Question I'm trying to model biclustering, but it's failing as it says array contains infs and nans, though I scanned array using pd.isnull(DataFile).sum() import pandas as pd import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import samples_generator as sg from sklearn.cluster.bicluster import SpectralCoclustering from sklearn.metrics import consensus_score DataFile=pd.read_csv("DatafilledProp.csv",sep='\t') DataFile.drop(DataFile.columns[[0, 1]], axis=1, inplace=True) plt.matshow(DataFile.as_matrix(), cmap=plt.cm.Blues) plt.title("Original TransMapping") data, row
  • Why is pydot unable to find GraphViz's executables in Windows 8?
    Question I have GraphViz 2.32 installed in Windows 8 and have added C:\Program Files (x86)\Graphviz2.32\bin to the System PATH variable. Still pydot is unable to find its executables. Traceback (most recent call last): File "<pyshell#26>", line 1, in <module> graph.write_png('example1_graph.png') File "build\bdist.win32\egg\pydot.py", line 1809, in <lambda> lambda path, f=frmt, prog=self.prog : self.write(path, format=f, prog=prog)) File "build\bdist.win32\egg\pydot.py", line 1911, in write dot_fd.write(self.create(prog, format)) File "build\bdist.win32\egg\pydot.py", line 1953, in create
  • Memory error when using pandas read_csv
    Question I am trying to do something fairly simple, reading a large csv file into a pandas dataframe. data = pandas.read_csv(filepath, header = 0, sep = DELIMITER,skiprows = 2) The code either fails with a MemoryError, or just never finishes. Mem usage in the task manager stopped at 506 Mb and after 5 minutes of no change and no CPU activity in the process I stopped it. I am using pandas version 0.11.0. I am aware that there used to be a memory problem with the file parser, but according to http://wesmckinney.com/blog/?p=543 this should have been fixed. The file I am trying to read is 366 Mb
  • Can no Longer open Spyder IDE for Python Programming
    Question I installed Python 3.4 on my Windows 7 laptop several months ago as part of Anaconda (https://www.continuum.io/downloads). My installation included the Spyder IDE, and I have successfully been using Spyder for Python programming. However, since yesterday, I have been unable to open Spyder. I typically open Spyder via the Start Menu, but now, when I try to click on the Spyder icon in the Start Menu, I get no response. I then tried to go directly to the spyder.exe file in the Scripts folder in the directory where Anaconda is installed. When I clicked on this the first time, the
  • Python 2.7: Unable to import matplotlib.pyplot
    Question When I tried to import matplotlib.pyplot as plt I was given the following error: runfile('/Users/Zhengnan/Documents/Python/PS 2/230I_PS_2.py', wdir='/Users/Zhengnan/Documents/Python/PS 2') Traceback (most recent call last): File "<ipython-input-2-9001323bba15>", line 1, in <module> runfile('/Users/Zhengnan/Documents/Python/PS 2/230I_PS_2.py', wdir='/Users/Zhengnan/Documents/Python/PS 2') File "/Users/Zhengnan/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile execfile(filename, namespace) File "/Users/Zhengnan/anaconda/lib
  • Error while reading a csv file in python using pandas [duplicate]
    Question This question already has answers here: Windows path in Python (5 answers) Closed 4 years ago. products = pd.read_csv('C:\amazon_baby.csv') Traceback (most recent call last): File "", line 1, in products = pd.read_csv('C:\amazon_baby.csv') File "C:\Users\kvsn\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 562, in parser_f return _read(filepath_or_buffer, kwds) File "C:\Users\kvsn\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 315, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "C:\Users\kvsn\Anaconda3\lib\site-packages\pandas\io\parsers.py", line
  • How to *correctly* read data from csv's into TensorFlow
    Question I came across this so posting showing us how to setup the code to read in csv files using a queue. However, each time I run it, I run into an error. I've tried debugging it, but can't figure out what the error means. Can anyone help me out? The code I'm using is almost verbatim what was posted in the above post: import tensorflow as tf dataset = '/Users/hdadmin/Data/actions/testing.csv' def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 def read_from_csv(filename_queue): reader = tf.TextLineReader(skip_header_lines=1) _, csv_row = reader.read
  • reading and doing calculation from .dat file in python
    Question I need to read a .dat file in python which has 12 columns in total and millions of lines of rows. I need to divide column 2,3 and 4 with column 1 for my calculation. So before I load that .dat file, do I need to delete all the other unwanted columns? If not, how do I selectively declare the column and ask python to do the math? an example of the .dat file would be data.dat I am new to python , so a little instruction to open , read and calculation would be appreciated. I have added the code I am using as a starter from your suggestion: from sys import argv import pandas as pd script
  • Mixed types when reading csv files. Causes, fixes and consequences
    Question What exactly happens when Pandas issues this warning? Should I worry about it? In [1]: read_csv(path_to_my_file) /Users/josh/anaconda/envs/py3k/lib/python3.3/site-packages/pandas/io/parsers.py:1139: DtypeWarning: Columns (4,13,29,51,56,57,58,63,87,96) have mixed types. Specify dtype option on import or set low_memory=False. data = self._reader.read(nrows) I assume that this means that Pandas is unable to infer the type from values on those columns. But if that is the case, what type does Pandas end up using for those columns? Also, can the type always be recovered after the fact?
  • python pandas dataframe head() displays nothing
    Question I am new to using pandas and I just don't know what to do with this : I am using python. I have (properly) installed anaconda. In my file I simply create a DataFrame (first by importing it from read_csv, then recreating it by hand to make sure that was not the problem). When I do print (dataframe) it prints: km | price 0 | 240000 | 3650 [...] 23 | 61789 | 8290 When I do dataframe.info() I get this : class 'pandas.core.frame.DataFrame' Int64Index: 24 entries, 0 to 23 Data columns (total 2 columns): km 24 non-null int64 price 24 non-null int64 dtypes: int64(2) memory usage: 576.0 bytes
  • Windows Error using XGBoost with python
    Question So I'm tackling this machine-learning problem (from a previous Kaggle competition for practice: https://www.kaggle.com/c/nyc-taxi-trip-duration) and I'm trying to use XGBoost but getting an error which I have no clue how to tackle. I searched on google and stack overflow but couldn't find anyone with a similar problem. I'm using python 2.7 with the Spyder IDE through Anaconda and I'm on Windows 10. I did have some trouble installing the xgboost package so I won't completely erase the idea that it could be an installation error. However I'm also doing a Udemy course on ML and I was
  • Comments in Python 3.5 giving unicode error
    Question I am using Spyder IDE , Python 3.5, which is a part of the anaconda distribution. Given below are the first few lines of the code: # -*- coding: utf-8 -*- """ Created on Tue Sep 20 16:22:40 2016 @author: pavan This program reads csv file from the given directory . The input directory for this is : "C:\Users\pavan\Documents\Python Scripts\EOD from Yahoo" The output file is "comprehensive_trend.xlsx" """ import pdb import pandas as pd from datetime import date, datetime, timedelta import os, glob # Delarations full_path = os.path.realpath(__file__) current_directory = os.path.dirname