2012-12-01 34 views
4

我有一个excel文件,我将其转换为带有数字列表的文本文件。Python。如何摆脱字符串中的' r'?

test = 'filelocation.txt' 

in_file = open(test,'r') 

for line in in_file: 
    print line 

1.026106236 
1.660274766 
2.686381002 
4.346655769 
7.033036771 
1.137969254 

a = [] 

for line in in_file: 
    a.append(line) 
print a 

'1.026106236\r1.660274766\r2.686381002\r4.346655769\r7.033036771\r1.137969254' 

我想将每个值(在每行中)分配给列表中的单个元素。相反,它会创建一个由\ r分隔的元素。我不确定\ r是什么,但为什么将这些放入代码中?

我想我知道一种方法来摆脱字符串中的\ r的,但我想从源头上解决问题

回答

5

要接受任何的\r\n\r\n,你可以使用'U'(通用换行符)文件方式换行:如果你想从该文件中的数字(浮点)阵列

>>> open('test_newlines.txt', 'rb').read() 
'a\rb\nc\r\nd' 
>>> list(open('test_newlines.txt')) 
['a\rb\n', 'c\r\n', 'd'] 
>>> list(open('test_newlines.txt', 'U')) 
['a\n', 'b\n', 'c\n', 'd'] 
>>> open('test_newlines.txt').readlines() 
['a\rb\n', 'c\r\n', 'd'] 
>>> open('test_newlines.txt', 'U').readlines() 
['a\n', 'b\n', 'c\n', 'd'] 
>>> open('test_newlines.txt').read().split() 
['a', 'b', 'c', 'd'] 

;看到Reading file string into an array (In a pythonic way)

0

您可以通过使用带剥去行回车和换行符()

line.strip() 

for line in in_file: 
    a.append(line.strip()) 
print a 
2

使用rstrip()rstrip('\r')如果你确定不是最后一个字符总是\r。在str.rstrip()

for line in in_file: 
    print line.rstrip() 

帮助:

S.rstrip([chars]) -> string or unicode 

Return a copy of the string S with trailing whitespace removed. 
If chars is given and not None, remove characters in chars instead. 
If chars is unicode, S will be converted to unicode before stripping 

str.strip()同时去除拖尾和先行空格。

+0

注:'.rstrip()'不会帮助,因为'线路在in_file'不承认'\ r'为有机磷农药的机器上一个换行符所以'line'可能包含多个内部'\ r',试试:''1 \ r2 \ r'.rstrip()' – jfs

0

为了解决这个问题吗:

for line in in_file: 
    a.append(line.strip()) 
0

.strip()行删除您不需要的空白:

lines = [] 

with open('filelocation.txt', 'r') as handle: 
    for line in handle: 
     line = line.strip() 
     lines.append(line) 

     print line 

print lines 

另外,我建议您使用with ...符号来打开一个文件。它更干净并自动关闭文件。

0

首先,我一般喜欢@ J.F。塞巴斯蒂安的答案,但我的用例更接近Python 2.7.1: How to Open, Edit and Close a CSV file,因为我的字符串来自文本文件从Excel输出为csv并进一步输入使用csv模块。截至该问题表示:

作为“儒的VS“RB” VS ...,CSV文件确实应该是二进制如此 使用“RB”。然而,从某些人将csv文件复制到Windows的记事本中并且随后将其与其他文件加入一些 以便您有时髦的行结尾的情况并不鲜见。您如何处理该 取决于您的文件和您的偏好。 - @kalhartt 1月23日3:57

我要坚持阅读'rb',建议在the python docs。现在,我知道单元格内部的\ r是我如何使用Excel的怪癖的结果,所以我将创建一个全局选项,用其他值代替'\ r',现在它将是' \ n',但后来可能是''(一个空字符串,不是双引号),只需简单的json更改。