Here's an example that brings together what is said in the comments, and also demonstrates how to use a with
such that you can be sure that the file gets closed properly. Using with
is the much preferred way to close files. Most notably, this will insure that the file is closed properly even when an exception is thrown inside the with
block.
import os
path = 'C:/Users/XXX'
files = os.listdir(path)
with open("write_demo.txt", 'w') as fp:
for f in files:
print(f)
zip_file_name = os.path.basename(f).split(".")[0]
print(zip_file_name)
fp.write(zip_file_name)
fp.write("\n")
print('Done Writing')
Note that f
will contain only each file's name, not the full path to the file. To process the file, you'd want to compute its full path with os.path.join(path, f)
. The fact that you are calling basename
on f
suggests that you think it contains the full path. Also, the way you are taking off the extension won't work if the file 's name contains multiple .
characters. A better way is zip_file_name, _ = os.path.splitext(f)
.