2017-09-27 53 views
0

我正在使用python 3.6.1。 我有一个目录充满了成千上万的文本文件。使用Python操作目录中的许多文本文件

我想删除每个文本文件中的前两行,而不是每个文本文件的新副本。

此外,我想删除每个文件中的最后一行,如果它们包含某个“关键字”,如果没有,那么最后一行不会被删除,仍然存在。

怎么办?

在此先感谢。

回答

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)     
+0

感谢,精美的作品。 :) – denis2887

0

我想使用的操作系统库就行了。

 

    import os 
    import re 

    path = r"&ltdirectory>" 

    #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 

希望这个作品为你

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])