是否有简单的方法可以在满足条件时为文件夹中的所有文件读取并添加新行
我有两个文件ABC.TXT和DEF.TXT,内容如下。
ABC.TXT
AAAAAA* TEST *
BBBBBB*=====================
CCC1QR RAQWERT
BBBBBB*=====================
RBBBBB =====================
MBBBBB =====================
DEF.TXT
RRR AA* TEST *
QWRRAB*=====================
CCC1QR 123QWE
BBBBBB*=====================
JBBBBB =====================
RBBBBB =====================
当一行的第7个位置有空格时,我需要添加2行(从位置8开始)并按原样重写文件。新行只在第一次在文件的位置7找到空格时添加一次。ABC.TXT
AAAAAA* TEST *
BBBBBB*=====================
CCC1QR RAQWERT
here is my line1
here is my line2
BBBBBB*=====================
RBBBBB =====================
MBBBBB =====================
DEF.TXT
RRR AA* TEST
QWRRAB*=====================
CCC1QR 123QWE
line1 added after first find of space
line2 added after first find of space
BBBBBB*=====================
JBBBBB =====================
RBBBBB =====================
感谢这是代码。沿途的注释将解释代码
files = ["ABC.txt","DEF.txt"]
for file in files: #Looping through all the files
f = open("ABC.txt", "r")
para = f.read()
spaceDetected = False #To ensure we add lines only one time
newPara = ""
for line in f.read():
if line[6] == " " and spaceDetected == false: # Checking if the letter at index 6, which is the 7th letter is a space and the 2 lines have not been added yet
newPara += line + " This is my line 1n This is my line 2n"#You may need to remove the newline from end and add one to the start
else:
newPara += line
w = file.open(file,"w")
w.write(newPara)
这将对所有文件进行排序,并执行您想要的操作。虽然这看起来确实像你的学校项目,但我有一些空闲时间