[英]How to write string in each line in txt file apart from the first one
I want to iterate through all txt files in a folder and add string to each line but the first one. 我想遍历文件夹中的所有txt文件,并将字符串添加到每一行,但第一行除外。
I have now: 我现在有了:
a|b|c|d|e|f
A | B | C | d |电子| F
1|2|3|4|5
1 | 2 | 3 | 4 | 5
I want to add eg 'X' 我想添加例如“ X”
a|b|c|d|e|f
A | B | C | d |电子| F
X|1|2|3|4|5
X | 1 | 2 | 3 | 4 | 5
import os
import glob
from pathlib import Path
cwd = os.getcwd()
directory = cwd
output = cwd
txt_files = os.path.join(directory, '*.txt')
for txt_file in glob.glob(txt_files):
cpath =(Path(txt_file).resolve().stem)
nametxt = "-".join(cpath.split('_')[0:1])
amendtext = "| " + nametxt
src=open(txt_file, errors='ignore')
lines = src.read().splitlines()
src.close
src = open(txt_file, "w")
src.write('\n'.join([amendtext +line for line in lines]))
尝试这个:
src.write('\n'.join([amendtext +line for i,line in enumerate(lines) if i>0 ]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.