簡體   English   中英

在Python中以分號分隔的txt文件中讀取

[英]reading in a semicolon delimited txt file in python

我正在嘗試逐行讀取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設置為分號分隔的行。 先感謝您。

您是否嘗試過使用split功能。 那應該給您一個列表,其中的行以;分隔; split函數將在字符串上使用,因此首先從文件中讀取完整數據。

字符串拆分示例:

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

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

>>> print lines

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

首先替換刪除換行符,然后拆分

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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM