我正在尝试解决以下问题:
readlines
.txt的list
if lin.startswith("2") and lin.endswith("|")
lin2 = lin + "ISENTO"
这是我到目前为止所得到的...
def editTxt():
#open .txt file and read the lines
filename = askopenfilename(filetypes=[("Text files","*.txt"), ("Text files","*.TXT")])
infile = open(filename, 'r')
infile.read()
#save each line in a list called "linhas" outside the editTxt function
with open(filename, 'r') as f:
linhas = f.readlines()
#create the output file
outfile = open(filename + "_edit.txt", 'w')
#checking the condition and writing the edited lines
for linha in linhas:
if linha.startswith("2") and linha.endswith("|"):
linha = linha + "ISENTO"
outfile.write(linha)
#close files
outfile.close()
infile.close()
问题是我的输出文件完全等于我的输入文件...
我已经尝试使用 if linha[0] == "2" and linha[len(linha)-1] == "|"
但是后来我发现模块f.readlines()
只是\n
在我的字符串之后添加...所以我尝试了if linha[0] == "2" and linha[len(linha)-3] == "|"
但是我也没有工作...
有些人告诉我,我应该使用replace函数。但是我不知道怎么做。
真实文件示例:
lin1 : 10 | 1,00 | 55591283000185 | 02/03/2015 | 31/03/2015
lin2: 20 | I ||销售| 0 | 9977 | 02/03/2015 00:00:00 | 02/03/2015 11:48:00 | 1 | 5102 ||| 07786273000152 |观察SEGURANCA LTDA | RUA MARINGA, | 2150 || BOA VISTA | RIBEIRAO PRETO | SP | 14025560 || 39121530 |
lin3: 30 | 1103 | DAT 05MM-5.102 || PC | 1.0000 | 19.9000 | 19.90 | 090 | 0.00 | 0.00 | 0.00
我只需要更改lin2,因为它以“ 2”开头,以“ |”结尾
运行editTxt函数后我需要什么:
lin2: 20 | I ||销售| 0 | 9977 | 02/03/2015 00:00:00 | 02/03/2015 11:48:00 | 1 | 5102 ||| 07786273000152 |观察SEGURANCA LTDA | RUA MARINGA, | 2150 || BOA VISTA | RIBEIRAO PRETO | SP | 14025560 || 39121530 | EXEMPT
请python专家,向我展示使用其他代码执行此操作的简便方法,或者最好向我解释我的问题。
谢谢!
您最近一次尝试非常接近
'\ n'行终止符实际上不是字符'\'和'n'。这是一个特殊字符,为方便起见用'\ n'表示。因此,它只是字符串中的一个字符,而不是两个。
希望,这应该给您足够的提示,以弄清楚如何更改您的代码:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句