1

I'm trying to write to a txt file but faced the following error message: [Errno 2] No such file or directory: 'results.txt'. The results.csv file contains data separated by pipeline delimiters. May I know what went wrong and how do I solve this?

results_path = "results.csv"
dest_path = "results.txt"

def row_count(results_path):
    return len(open(results_path).readlines())

def add_header_footer(results_path, dest_path, file_name, date_today):
    with open(results_path) as from_file, open(dest_path) as to_file:
        header = 'H|ABC|' + file_name + '|' + date_today + '\n'
        footer = 'E|' + str(row_count(results_path)) + '|\n' 

        to_file.write(header)
        shutil.copyfileobj(from_file, to_file)
        to_file.write(footer)

add_header_footer(results_path, dest_path, 'Results_Today', '20190818')
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

3

You should use open destination file with the w+ mode. It tries to write to the file and if it does not exist then it creates the file. Change this part of your code and see whether it works.

open(dest_path, 'w+') as to_file

There are other modes too like, a+ for appending. Read more here

Shababb Karim
  • 3,614
  • 1
  • 22
  • 35
0

Python can find your file result_path.

Try to set your results_path variable as an Absolute path.

Normally that Error message is shown when you call a file which is not in the same level as your py file.

Hope this is helpful! :D

Kevin Quinzel
  • 1,430
  • 1
  • 13
  • 23