Python 在固定宽度文本文件的多个位置添加分隔符时出现问题
我试图在下面列表中给出的多个位置的固定宽度文本文件中添加分隔符。我正在使用python 3.4.4 文件: 因为,一个文件中有1000行,所以我试图通过迭代列表并将其添加到Python 在固定宽度文本文件的多个位置添加分隔符时出现问题,python,python-3.x,list,text-files,delimiter,Python,Python 3.x,List,Text Files,Delimiter,我试图在下面列表中给出的多个位置的固定宽度文本文件中添加分隔符。我正在使用python 3.4.4 文件: 因为,一个文件中有1000行,所以我试图通过迭代列表并将其添加到newline变量中来实现这一点,但是没有在适当的位置添加分隔符 代码: 电流输出:是否产生错误 output.txt @4a5|4667inthenationof pr @4a54667|inthenationof pr @4a54667int|henationof pr @345|3343bewithmeincaseof
newline
变量中来实现这一点,但是没有在适当的位置添加分隔符
代码:
电流输出:是否产生错误
output.txt
@4a5|4667inthenationof pr
@4a54667|inthenationof pr
@4a54667int|henationof pr
@345|3343bewithmeincaseof@3453343|bewithmeincaseof@3453343bew|ithmeincaseof
预期输出:固定位置4、8和11处的分隔符
@4a5|466|7i|nthenationof pr
@345|334|3b|ewithmeincaseof
问题是,您在迭代
列表中的项目时正在写入输出文件。下面的代码应该可以解决这个问题。另外,尽量避免使用关键字作为变量名,因此将list
重命名为其他名称
代码
positions=[4,8,11]
以open('output.txt','w')作为输出文件:
以open('a.txt','r')作为填充:
对于填充中的线:
换行符
对于处于以下位置的l:
换行符=换行符[:l]+“|”+换行符[l:]
outfile.write(换行符)
输出
@4a5|466|7i|nthenationof pr
@345|334|3b|ewithmeincaseof
首先,我建议不要使用内置变量名,因此我建议将list
重命名为类似positions
的名称。下一步:
for l in positions:
newline = line[:l] + '|' + line[l:]
outfile.write(newline)
试着在你的头脑中跑步你在这里做什么:
- 每个职位的职位
- 将“
换行符”
设置为原始行,并在该位置使用分隔符
- 使用单个分隔符按原样将
换行符写入文件
所以基本上,对于每个位置,你都要在那个位置复制线条。这可能更接近您的意思(不使用任何Python恶作剧):
注意,由于newline
不断变大,我必须不断增加pos
来考虑这一点。还请注意,当我修改完行时,我正在写作。要避免簿记,您可以反向操作:
for pos in positions[::-1]:
newline = newline[:pos] + '|' + newline[pos:]
从现在起,换行符在当前插入位置之后变长。最后是恶作剧:
newline = line
pos_counter = 0
for pos in positions:
pos += pos_counter
newline = newline[:pos] + '|' + newline[pos:]
pos_counter += 1
outfile.write(newline)
newline = '|'.join(line[start:stop] for start, stop in zip([0]+positions, positions+[-1]))
我认为输出文件中为4的输出是由于for循环
造成的,为了消除它,您应该将outfile.write()
放在第一个for循环
中。由于要将管道符号“|”插入到4、8和11位置,您只需将其插入到行列表中,然后连接以写入新的输出文件
lit=[4,8, 11]
with open('output.txt', 'w') as outfile:
with open('a.txt', 'r') as infile:
for line in infile:
line = list(line)
for i in lit:
line.insert(i,'|')
outfile.write("".join(line))
outfile.close()
这是另一种使用.insert
Ex:
lst=[4,8, 11]
with open(filename_1) as infile, open(filename_2, 'w') as outfile:
for line in infile:
line = list(line)
for p in lst:
line.insert(p, "|") #insert `|` @ given pos
outfile.write("".join(line)) #join & write
@4a5|466|7i|nthenationof pr
@345|334|3b|ewithmeincaseof
输出:
lst=[4,8, 11]
with open(filename_1) as infile, open(filename_2, 'w') as outfile:
for line in infile:
line = list(line)
for p in lst:
line.insert(p, "|") #insert `|` @ given pos
outfile.write("".join(line)) #join & write
@4a5|466|7i|nthenationof pr
@345|334|3b|ewithmeincaseof
pos+=1
是不必要的。OP已经解释了字符串大小的增加,这是由于在他的列表中添加了带值的分隔符,这就是为什么第二个是8而不是7,第三个是11而不是9。您能详细说明代码的第四行吗?line=list(line)
我正在将str
转换为列表
,这样就可以使用插入
方法。我不确定您的最终输出是否是您的意思,因为如果位置是原始文件中的位置,例如,第一行的预期输出应该是:@4a5 | 4667 | int | henationof pr
。变量名不应该使用list
等关键字。
@4a5|466|7i|nthenationof pr
@345|334|3b|ewithmeincaseof