我正在使用python 3.6.1。 我有一个目录,里面有成千上万的文本文件。
我想删除每个文本文件中的前两行,而不是为每个文本文件创建一个新副本。
此外,我想删除每个文件中的最后一行,如果它们包含某个"关键字",如果没有,那么最后一行不会被移除并且仍在那里。
怎么做?
提前致谢。
答案 0 :(得分:0)
试试这个(我假设文本文件至少有3行):
import glob
path = r"./" #Type your PATH here or run the script in your files' directory
filenames = glob.glob(path + "*.txt")
keyword = "keyword"
for file in filenames:
with open(file) as f:
lines = f.readlines()
lines = lines[2:] #Delete first and second line
if keyword in lines[len(lines) - 1]:
lines = lines[:-1] #Delete last line if necessary
with open(file, "w") as f:
for line in lines:
f.write(line)
答案 1 :(得分:0)
我认为使用os库可以。
import os import re path = r"<directory>" #now you could print everything inside the directory print(os.listdir(path)) #to print each item separately for roots, dirs, files in os.walk(path): #the roots will select all the roots, dirs will select the directories #inside your directory and files will select only the files inside #your directory #to get the files for file in files: #you can print all filenames for test purpose print("File = %s", file) #now you have the string names of all files, all that is left to do #is parse them using regular expressions. parts = re.split("\.",file) #this will spit the string after the period #the parts variable will now have two parts, first part containing #the file name and the second part containing the file extension. if(parts[1]=="txt"): f = open(file,"w") #now you can do whatever you want with the file
希望这对你有用
答案 2 :(得分:0)
您只需使用python os module
并对目录中的每个文本文件执行操作:
import os
path = "Your directory path"
for file in os.listdir(path):
if file.endswith(".txt"):
lines = open(file).readlines()
open(file, 'w').writelines(lines[2:])
if keyword in lines:
open(file, 'w').writelines(lines[:-1])