我正在尝试逐行读取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 :(得分:1)
您是否尝试使用split
功能?这应该会给你一个列表,其中的行用;
分隔。 split
函数将用于字符串,因此首先从文件中读取完整的数据。
字符串拆分示例:
>>> a = "test;this;string;"
>>> lines = a.split(";")
>>> print lines
['test', 'this', 'string', '']
答案 1 :(得分: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']