import os input_dir = '/var/data' output_file = '/var/result/data.txt' def get_first_line_from_files(input_directory, output_path): with open(output_path, 'w') as outfile: for filename in os.listdir(input_directory): file_path = os.path.join(input_directory, filename) if os.path.isfile(file_path): with open(file_path, 'r') as infile: first_line = infile.readline().strip() outfile.write(first_line + '\n') if __name__ == "__main__": get_first_line_from_files(input_dir, output_file)