我有一个文件,其中有许多以“|”结尾的字段 (管道)字符。我想读取这个文件并创建与特定字段的值一样多的文件。这里有一个例子:
L219| |791|P|PIPPO|PLUTO|1|18081926|I262|XYZXCV12D35F345S||
L219| |1241|P|PAPERINO|TOPOLINO|2|21041937|F335|FVGHWU54G56S456U||
L219| |437793|G|TOPOLANDIA SAS|L219|12345678910|
L219| |437794|G|PAPERANDIA|L219|10987654321|
如果第四个字段等于“G”,则记录进入“file_pg.txt”,否则如果等于“P”,则进入“file_pf.txt”。
我写了下面的代码(我是 Python 新手),但是执行大尺寸(300mb)的文件需要很长时间,你有什么改进的建议吗?
file = open('D:\\mydirectory\\soggetti.txt','r')
file_pf = open("D:\\mydirectory\\file_pf.txt","w")
file_pg = open("D:\\mydirectory\\file_pg.txt","w")
file_pf.close()
file_pg.close()
i = 0
with file:
for line in file:
i = 0
c = 0
while i < len(line):
carattere = line[i]
if carattere == "|":
c = c + 1
if c == 4:
if line[i-1] == "P":
file_pf = open("D:\\mydirectory\\file_pf.txt","a")
file_pf.write(line)
file_pf.close()
break
elif line[i-1] == "G":
file_pg = open("D:\\mydirectory\\file_pg.txt","a")
file_pg.write(line)
file_pg.close()
break
i = i + 1
file.close()
谢谢!
阿尔贝托