Search code examples
python-3.xfor-loopwhile-loopstrip

Strip leading and trailing spaces on 851 files in Python


I would like to strip leading and trailing spaces from my 851 files. How can I do this? The first file is made up of 220 lines. The last file is made up of 1315 lines. I tried:

x = 1
while x < 852:
    f = open("final.%d.txt" % x)
    lines = f.readlines()
    for i in range(0,row+1):
        str_a = lines[i]
        print(str_a.strip())
    x = x + 1

But it only outputs 851 filenames.


Solution

  • I'm not entirely sure what you want to do but I will suppose that:

    • You want to read the content of 851 files name final.1.txt, final.2.txt, final.3.txt, etc.
    • For each of these file you want to strip all the trailing and leading spaces fore every line in that file
    • You want to save it in a new file.

    I will now provide you with a solution that writes the files without white space in another directory. This way you won't overwrite your input files if this is not what your wanted. If my assumptions are wrong, could you be more precise about what you want to do?

    import os, os.path
    
    output_directory = "files_stripped"
    os.makedirs(output_directory, exist_ok=True)
    
    for x in range(1, 852):
        input_file_name = f"final.{x}.txt"
        output_file_name = os.path.join(output_directory, f"final.{x}.txt")
        with open(input_file_name) as input_file:
            with open(output_file_name, "w") as output_file:
                for input_line in input_file:
                    output_line = input_line.strip()
                    output_file.write(output_line + "\n")