【问题标题】:.txt file is acting weird under readlines().txt 文件在 readlines() 下表现得很奇怪
【发布时间】:2013-01-03 13:31:22
【问题描述】:

文件内容如下:

1/15/13,930,1441.5
1/15/13,1000,1442.75
1/15/13,1030,1444

我跑:

the_txt_file = open('/txt_file')   

然后我运行:

the_txt_file_as_a_list =  the_txt_file.readlines()

然后我运行:

print the_txt_file_as_a_list

我明白了:

['1/15/13,930,1441.5\r1/15/13,1000,1442.75\r1/15/13,1030,1444\r1/']

但我期待的是这样的:

['1/15/13,930,1441.5\n','15/13,1000,1442.75\n','15/13,1030,1444\n']

这种情况经常发生在我身上,这是怎么回事?

【问题讨论】:

  • $ xxd /txt_file 看看文件有没有问题
  • 文件好像有回车符(\r)但没有换行符(\n)。
  • 我该如何解决这个问题?
  • 使用“rU”模式打开文件
  • 所以:the_txt_file = open('/txt_file', rU) ?

标签: text python-2.7 textedit readlines


【解决方案1】:

所以问题似乎与我的 mac 与 .txt 文件交互的方式有关

问题已通过交换解决:

the_txt_file = open('/txt_file')   

与:

the_txt_file = open('/txt_file', 'rU')

“rU”被称为“通用读线”。以“rU”模式打开文件是以通用读取线模式打开文件。运行时:

the_txt_file_as_a_list =  the_txt_file.readlines()

然后:

print the_txt_file_as_a_list

我的输出来自:

['1/15/13,930,1441.5\r1/15/13,1000,1442.75\r1/15/13,1030,1444\r1/']

到:

['1/15/13,930,1441.5\n', '1/15/13,1000,1442.75\n', '1/15/13,1030,1444\n']

后来,我能够通过以下方式分别打印每个项目:

for item in the_txt_file_as_a_list:
    print item

输出看起来像:

1/15/13,930,1441.5

1/15/13,1000,1442.75

1/15/13,1030,1444

【讨论】:

    【解决方案2】:

    我假设您或此数据文件的原始创建者使用的是 Mac。似乎您期望它是一个简单的 '\n' 行结尾,但会受到原始编辑器系统默认行结尾的影响(很可能)。

    一个简单的解决方法是使用rU 选项调用open(...),如下所示:

    the_txt_file = open('/txt_file', 'rU')

    这确保文件以r只读方式打开,并在读取特定文件时使用U通用换行支持。

    祝你好运!

    【讨论】:

    • 这非常有效。我通过单独做两件事对其进行了测试:1. 打印 the_txt_file 2. 对于 the_txt_file 中的项目:打印项目
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 2012-11-11
    相关资源
    最近更新 更多