import os
target = 'c:\\Python38-64'
report = open('specific-ext.txt', 'w')
for root, dirname, files in os.walk(target):
for x in files:
if x.endswith('.txt'):
report.write(root + '\\' + x + '\n')
report.close()
This code walks through the directory tree rooted at c:\\Python38-64
, and for each file found with a .txt
extension, it writes the full path of the file (composed of the root directory and the filename) to a file named specific-ext.txt
.
First, it opens a new file named specific-ext.txt
in write mode using the open()
function. Then it loops through each directory, subdirectory, and file within the root directory using the os.walk()
function. For each file found, it checks if its extension is .txt
using the endswith()
method of strings. If the extension is .txt
, it writes the full path of the file to the specific-ext.txt
file using the write()
method of the file object. Finally, it closes the file using the close()
method.
No comments:
Post a Comment