2015-07-01 174 views
-1

我试图读取python中的.txt文件,逐行。在python中读取分号分隔的txt文件

out=open('output_path\A.txt','w') 

with open('input_path\B.txt','r') as foo: 
    for each_line in foo: 
     #modify each line 

一个问题是我希望每一行都是用分号分隔符而不是行更改来定义的。我会怎么做?

这是txt文件的样子,例如:

%IF (&YEAR LT 2010) %THEN %DO; 

    PAYLC3=(1.08**(1/12)-1)*X1617; 

    IF (X1918>0) THEN PAYORE3= 
    (X1903 IN (12,14,21,22,25,40,41,42,43,44,49,50,52,999))* 
    X1918*(%MCONV(F=X1919))*(X1905/10000);  
    ELSE IF (X1923>0) THEN PAYORE3= 
    (X1903 IN (12,14,21,22,25,40,41,42,43,44,49,50,52,999))* 
    X1923*(%MCONV(F=X1924))*(X1905/10000); 
    ELSE PAYORE3=0; 
%END; 

我希望能够设置each_line为分号分隔线。先谢谢你。

+0

首先将它们连接在一起,然后仅在';'上进行分割。 (没有评论或字符串?这使它更容易!) – usr2564301

回答

1

您是否尝试过使用split函数。这应该给你一个列表,用;分隔的行。 split函数将用于一个字符串,所以首先从文件中读取完整的数据。

字符串分割示例:

>>> a = "test;this;string;"

>>> lines = a.split(";")

>>> print lines

['test', 'this', 'string', '']

+0

gotcha。谢谢! – chungkim271

0

第一替换除去换行符然后分裂

a = 'this thing\n the same thing in another line\n;the other thing; and other' 
print a 
# this thing 
# the same thing in another line 
#;the other thing; and other 

b = a.replace('\n','').split(';') 
# b = ['this thing the same thing in another line', 'the other thing', 'and other'] 
相关问题