2015-07-01 178 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'] 
相關問題