【python】批量读取txt,并在文件开头和每一行末尾添加字符

2018-09-12  本文已影响101人  yuanCruise
from PIL import Image

#file.txt中存的是我需要批量读取的txt的绝对路径
lines = open("file.txt").readlines()
for line in lines:
     line = line.strip()#把每个绝对路径最后的换行符去掉
     jpg_name = line.replace(".txt",".jpg")
     img = Image.open(jpg_name)
     #print line
     #打开每个txt进行操作
     with open(line) as f:
          f_lines = f.readlines()
          for i in range(0,len(f_lines)):
                f_lines[i] = "change_str" + f_lines[i].strip() +"change_str"+"\n"
      with open(line,"w") as f2:
          f2.writelines(f_lines)
      with open(line,"r+") as f3:
          content = f2.read()
          f3.seek(0,0)
          str_ = "Note\n"
          f3.write(str_+content)

f.seek(0, 0)不可或缺,file.seek(off, whence=0)在文件中移动文件指针, 从 whence ( 0 代表文件其始, 1 代表当前位置, 2 代表文件末尾)偏移 off 字节

上一篇下一篇

猜你喜欢

热点阅读