简体   繁体   English

打开文件并读取数据

[英]opening a file and reading data

So I am using these lines of code to read an Excel file. 因此,我正在使用这些代码行来读取Excel文件。

fin=open("C:\Users\Student\Desktop\Python Coding\bodyfat.csv",'rU')
fin.readline()

However I keep getting this error statement and I have no idea what is going on 但是我一直收到这个错误声明,我不知道发生了什么

>>> fin=open("C:\Users\Student\Desktop\Python Coding\bodyfat.csv",'rU')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] invalid mode ('rU') or filename: 'C:\\Users\\Student\\Desktop\\Python Coding\x08odyfat.csv'
>>> fin.readline()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fin' is not defined

Any idea on what is going on here? 对这里发生的事情有任何想法吗?

You are not escaping string backslashes properly. 您没有正确转义字符串反斜杠。 Notice in the traceback it says "Coding\\x08odyfa". 注意,在回溯中它显示为“ Coding \\ x08odyfa”。 You can use raw strings 您可以使用原始字符串

r"C:\Users\Student\Desktop\Python Coding\bodyfat.csv"

or escape the escape char 或逃脱逃逸字符

"C:\\Users\\Student\\Desktop\\Python Coding\\bodyfat.csv"

The first error occurs because, in standard Python strings, backslashes do interesting things to the characters that follow them (see the documentation on string literals for details): 发生第一个错误是因为在标准Python字符串中,反斜杠会对后面的字符产生有趣的影响(有关详细信息,请参见字符串文字的文档 ):

>>> "C:\Users\Student\Desktop\Python Coding\bodyfat.csv"
'C:\\Users\\Student\\Desktop\\Python Coding\x08odyfat.csv'
                                         # ^ what?

The second error occurs because, after the first error occurs, fin is never assigned. 发生第二个错误的原因是,在第一个错误发生之后,从未分配fin

The simplest fix is to use "raw strings", prefixed with an r , to indicate that backslashes should be treated as normal characters: 最简单的解决方法是使用以“ r ”为前缀的“原始字符串”来指示反斜杠应被视为普通字符:

>>> r"C:\Users\Student\Desktop\Python Coding\bodyfat.csv"
'C:\\Users\\Student\\Desktop\\Python Coding\\bodyfat.csv'

(Don't worry about the doubling, that's just Python's way of indicating that those are literal backslashes, rather than escaping the characters that follow.) (不必担心加倍,这只是Python表示那些是文字反斜杠的方式,而不是转义后面的字符。)

Also, you should use the with "context manager" for file handling: 另外,您应使用with “上下文管理器”的文件处理:

with open(r"...") as fin:
    line = fin.readline()
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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