Wednesday, August 31, 2022

Python - borrar lineas extra de archivos .txt en un directorio

 Aqui el codigo Python para borrar lineas extra en un archivo plano:


import os

path = "c:\\temp"

path_new='c:\\temp\\CleanFiles'

for x in os.listdir():

  if x.endswith('.txt'):

# Prints only text file present in My Folder

    print(x)

    f = open(x)

    new_file_str = path_new + '\\' + x

    f_new = open(new_file_str,'w')

    line = f.readline()

   # include newline

    while line:

      transfer_line = True

      line = line.rstrip()

  # strip trailing spaces and newline

      if  line == "":

        transfer_line = False

      if  transfer_line == True:

        line_new = line + '\n'

        f_new.write(line_new)

      line = f.readline()

    f.close()

    f_new.close()

No comments:

Post a Comment

Python - borrar lineas extra de archivos .txt en un directorio

 Aqui el codigo Python para borrar lineas extra en un archivo plano: import os path = "c:\\temp" path_new='c:\\temp\\CleanFile...