2017-09-27 2 views
0

J'utilise python 3.6.1. J'ai un répertoire rempli de milliers de fichiers texte. Je veux supprimer les 2 premières lignes dans chaque fichier texte, sans faire une nouvelle copie de chaque fichier texte.Manipulation de nombreux fichiers texte dans un répertoire utilisant Python

En outre, je veux supprimer la dernière ligne dans chaque fichier s'ils contiennent un certain "mot-clé", sinon, la dernière ligne n'est pas supprimée et toujours là.

Comment le faire?

Merci d'avance.

Répondre

0

Essayez ceci (je suppose des fichiers texte ont au moins 3 lignes):

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

grâce, fonctionne à merveille. :) – denis2887

0

Je pense en utilisant la bibliothèque os fera.

 

    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 

espère que cela fonctionne pour vous

0

Vous pouvez simplement utiliser le python os module et effectuer l'opération sur chaque fichier texte dans le répertoire:

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