Python import CSV file appears syntaxerror problem analysis _python

Source: Internet
Author: User
This article mainly describes the Python import CSV file syntaxerror problem analysis, while involved in Python import CSV file three ways, with some reference value, for Python interested friends can refer to.

Background

Np.loadtxt () is used to load data from text.

Each line in a text file must contain the same data.

***

loadtxt(fname,dtype=<class'float'>,comments='#',delimiter=None,converters=None,skiprows=0,usecols=None,unpack=False,ndmin=0)

fnameThe file, file name, or generator to read.

dtypeData type, default float.

commentsComments.

delimiterDelimiter, the default is a space.

skiprowsSkips the first few lines of read, default is 0, must be int integer.

usecols: Which columns to read, 0 is the first column. For example, usecols= (1,4,5) will fetch columns 2nd, 5th, and 6th. All columns are read by default.

unpackIf True it is, it will be read in columns.

Problem

When I read a file in Ipython today,

The code is:


Import NumPy as Npx = Np.loadtxt (' C:\Users\sunshine\Desktop\scjym_3yNp3Gj\ source data \000001.csv ', delimiter= ', ', skiprows= (1 ), usecols= (1,4,6), unpack= False)


The following error occurred:


SyntaxError: (Unicode error) ' Unicodeescape ' codec can ' t decode bytes in position 2-3: truncated \uxxxxxxxx escape


Coding errors, after searching for problems, found the following solutions:


R ' C:\Users\expoperialed\Desktop\Python ' C:\\users\\expoperialed\\desktop\\python ' c:/users/expoperialed/ Desktop/python '


Seeing here, I knew where I was wrong.

There are several points to note in writing a string:

1. Long string

A very long string, which spans multiple lines, can use three quotation marks instead of plain quotation marks.

That


Print ("This is a very long string.it would continue.and it's not over yet." Hello,world ' Still here. '


It can be noted that in this way, both single and double quotes can be used in a string

2. Original string

Thatprint(r'c:\nwhere')

The backslash has a special effect, it escapes, and it helps us to add single quotes and double quotes to the string that cannot be added directly.

\ n, a newline character, which can be stored in a string.

In the code block above, obviously we want a path, and if we don't use the original string, we'll get

c:where。

Yes, to prevent this, we can also use backslashes to escape, but if the path is long, it's like the path to this article:

C:\\\Users\\\sunshine\\\Desktop\\\scjym_3yNp3Gj\\\源数据\\\000001.csv

With a double slash, it can be cumbersome.

At this point, we can use the original string.

The original string starts with R.

The original string end cannot be a backslash.

To end with a backslash, print(r'C:\Programfiles\foo\bar''\\') i.e.C:\Programfiles\foo\bar\

In a regular Python string, the \u character combination represents an extended Unicode code point escape.

So there was an error here.

Three ways to import a CSV file from Python


#原始的方式lines = [Line.split (', ') for line in open (' iris.csv ')]df = [[Float (x) for x in Line[:4]] for line in Lines[1:]] #使用nu Mpy Package Import numpy as Nplines = Np.loadtxt (' iris.csv ', delimiter= ', ', ' dtype= ' str ') df = lines[1:,:4].astype (' float ') # Use Pandas package Import pandas as Pddf = Pd.read_csv (' iris.csv ') Df=df.ix[:,:4]


The last of these three methods is the simplest, but takes longer, the first is the most troublesome, but the shortest time. This can be seen through the magic function in Ipython %%timeit .

Summarize

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.