为什么Python 2.7.3认为我的.csv文件都在一行? [英] Why does Python 2.7.3 think my .csv document is all on one line?

查看:184
本文介绍了为什么Python 2.7.3认为我的.csv文件都在一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,在某些作业中遇到了一些问题,我无法理解。考虑一个名为example.csv的假想文件,内容如下:

pre code $ Key1,Value1
Key2,Value2
Key3,Value3
...

如果我运行下面的代码,打印文件中的每一行,然后在最后一行打上一个星号。我期望它打印每一行用星号分隔。

  infile = open(example.csv,r)
for infile中的行:
print line.strip()
print'*'
#row_elements = line.split(,)
#print row_elements

另外,如果我试图通过去掉上面代码中的哈希来拆分每一个逗号的行,我会得到如下的输出:

  ['Key1','Value1\rKey2','Value2\rKey3'... 
pre>

通过将\r传递给.split()方法,输出略有改善。

  ['Key1,Value1','Key2,Value2'... 

我仍然不明白为什么python认为整个文件都在一行。有没有人有这方面的见解?

解决方案您的文件正在使用 \r 作为行分隔符(也称为CR或Classic Mac换行符)。 Python的打开不会默认处理这个。



你可以使用universal newlines模式

'rU'> 打开 (请注意,一些Mac文本编辑器仍然使用 \ r 作为行结束符,尽管这些现在比几年前要少得多。)


I'm new to programming and I encountered a problem in some of my coursework that I can't make any sense of. Consider an imaginary file called 'example.csv' with the following contents.

Key1,Value1
Key2,Value2
Key3,Value3
...

If I run the following code, it prints every line in the file followed by a single asterisk on the last line. I expected it to print each line separated by an asterisk.

infile = open("example.csv", "r")
for line in infile:
    print line.strip()
    print '*'
    #row_elements = line.split(",")
    #print row_elements

Furthermore, if I try to split the line at each comma by removing the hashes in the above code I get the following output.

['Key1', 'Value1\rKey2', 'Value2\rKey3'...

By instead passing "\r" to the .split() method the output is slightly improved.

['Key1,Value1', 'Key2,Value2'...

I still don't understand why python thinks the entire file is all on one line in the first place. Does anyone have insight into this?

解决方案

Your file is using \r as line separators (also known as the "CR" or "Classic Mac" newline convention). Python's open doesn't deal with this by default.

You can use "universal newlines" mode ('rU' mode in open) to open the file properly.

(Note that some Mac text editors still use \r as the line terminator, though these are thankfully much less common now than they were a few years ago.)

这篇关于为什么Python 2.7.3认为我的.csv文件都在一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆