简体   繁体   中英

Python using type in place of cat

I'm currently working through Wes McKinney's Python for Data Analysis book. I ran into a problem on one of his examples on chapter 6.

His entry into Jupyter:

!cat examples/cs1.csv
a,b,c,d,message
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo

There is a short box afterwards that says if you're using Windows, to use the type command in place of cat. I entered the following:

!type examples/ex1.csv
a,b,c,d,message
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo

But got an error: "NameError: name 'a' is not defined."

How do I use the type command in place of cat for this instance? Running Python 3.6.5 on Windows 10.

The command is !type examples/ex1.csv . The remaining four lines are the contents of the file in question.

In their simplest usage, the windows type and Unix cat commands output the contents of the file named in the argument to standard output.

The prefix ! tells IPython/Jupyter to send the remainder of the line to the system shell instead of the Python interpreter.

Usually, when showing an entire session with both input and output, some sort of indication is given as to which lines are inputs and which are outputs. IPython sessions usually prefix the input with In[1]: and the output with Out[1]: . Plain Python sessions generally prefix input with >>> . In this case, it appears that the user is left to infer from context.

As a matter of interest, the following pure Python code would have the same result:

with open('examples/ex1.csv') as f:
    for line in f:
        print(line)

OR

with open('examples/ex1.csv') as f:
    print(f.read())

We are reading the same book. I have now started Chapter 6.

This error you received, I solved it with the following syntax:

!type examples\ex1.csv

Note the backslash.

Hope this helps.

!type+path is used for read the existed data instead of writing the data into the file.

the following content is what you read from the CSV file, you should not type this.

a,b,c,d,message 1,2,3,4,hello 5,6,7,8,world 9,10,11,12,foo

you can download those csv files from GitHub

I've recently read past the Chapter 6 of Wes McKinney's Python for Data Analysis. Wes used !type examples/ex1.csv for Unix environment.

For Windows, ignore the Unix code and, rather use pd.read_csv('examples/ex1.csv') to read the csv file.

You can create your own ex1.csv file or download the book's supporting files on Wes' GitHub page.

You can use %pycat if you have an updated jupyter release. It will display the result as a footer window in your browser, not ideal but at least you can see the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM