0

I have the following code:

# function to truncate files
def truncate(path):
    file_to_truncate = open(path, "w")
    file_to_truncate.truncate()
    file_to_truncate.close()


# truncate all relevant files so they are empty and new results are not written underneath another set of results
truncate(r'outputA.csv')
truncate(r'\outputB.csv')
truncate(r'outputC.csv')
truncate(r'outputD.csv')
truncate(r'outputE.csv')
truncate(r'MoutputA.csv')
truncate(r'MoutputB.csv')
truncate(r'MoutputC.csv')
truncate(r'MoutputD.csv')
truncate(r"Full Results.csv")
truncate(r'results.csv')

Is it possible to shorten this code i.e truncate all files in the directory.

PythonIsBae
  • 368
  • 3
  • 10
  • Check out the [`os`](https://docs.python.org/3/library/os.html) and [`pathlib`](https://docs.python.org/3/library/pathlib.html) libraries. – 0x5453 May 25 '20 at 21:29
  • Does this answer your question? [How can I iterate over files in a given directory?](https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory) – azro May 25 '20 at 21:29
  • 1
    Also, since this is a destructive operation, I would comment out the contents of the `truncate` function (just put a `print` or something in there instead) until you are sure your script will operate on all of the correct files. Don't want to accidentally truncate things in the wrong directory. – 0x5453 May 25 '20 at 21:31
  • @0x5453 I need to truncate all the files for the script to work correctly but thanks. – PythonIsBae May 25 '20 at 21:34

1 Answers1

1

You can use os.listdir to get all the files in a particular directory. Then iterate over the list of files and call your function on them:

for file_name in os.listdir():
    truncate(file_name)
Milan Cermak
  • 7,476
  • 3
  • 44
  • 59