Python – Create output files from an input file that has the same name as it for all file in a directory

Question:

Good morning.
I would need a script that reads information in one file and reports it in an order I indicated in another text file.
With simple input/output statements I managed to do it but the problem is that I need this to be done for all the files in the directory and that each output produced has the same name as the file from which it comes.
Could someone help me?
I am new to Python but I have to learn quickly for my master’s thesis work.

I describe the problem in more detail.
I have a directory with about 7000 files with the .xyz extension that consist of a variable number of rows. I have to discard the second line and copy the remaining ones into a new file with different extension by adding text and converting all the letters ‘H’ of the lines to ‘1’.
I would also like each new .txt file to have the same name as the .xyz file from which it was generated and to be saved in a different directory.

This is the following working code but it is for only one file at a time:

c_input=open('C:/.../test_input.txt', 'w')
c_input.write('MOLECULE')
c_input.write('n')
c_input.write('1')
c_input.write('n')

file_to_read=open('C:/.../Water_1.xyz', 'r')
a=file_to_read.readline()
c_input.write(a)
list_file_to_read=file_to_read.readlines()
for i in range(len(list_file_to_read)):
    if i>0:
        c_input.write((list_file_to_read[i]))
file_to_read.close()
c_input.close()

c_input=open('C:/.../test_input.txt', 'r')
file_source=c_input.read()
c_input.close()
c_input=open('C:/.../test_input.txt', 'w')
replace_string=file_source.replace('H', '1')
c_input.write(replace_string)
c_input.close()

Asked By: Mat

||

Answers:

import os

# Constants for program
# These folders must exist before runtime
new_text_file_path = "C:\path\to\new_text_files"
xyz_files_path = "C:\path\to\xyz_files"

# Get the list of ".xyz" files in the "xyz_files_path" directory
xyz_files = [file for file in os.listdir(xyz_files_path) if os.path.isfile(os.path.join(xyz_files_path, file)) and ".xyz" in file]

# For each file in that directory:
for file in xyz_files:
    # Open the ".xyz" file
    with open(file, "r+") as handle:
        # Create a list of lines, replacing each "H" with "1" in each line
        data = [line.replace("H", "1") for line in file.readlines()]
        
        # Delete the second element in the list
        del data[1]
        
        # Create a new filename, with the same as the original, except ".txt" at the end.
        new_filename = file.replace(".xyz", ".txt")

        # Open the new file in a write handler
        with open(os.path.join(new_text_file_path, new_filename), "w+") as new_handle:
            # Write the replaced data into the new file.
            new_handle.write(''.join(data))
        
Answered By: Nulla