Monday, April 21, 2025

Exporting Directory Listing to .TXT File - Python

import os

path = 'c:\\Python38-64\\DLLs'

file = open('simple-report.txt', 'w')

for x in os.listdir(path):
    file.write(x + '\n')

file.close()

This Python code imports the "os" module.

It assigns a string path 'c:\Python38-64\DLLs' to the variable "path". This variable represents the path of a directory that contains files.

The code then uses the "open" function to create a new text file named "simple-report.txt" in write mode (indicated by the 'w' argument) and assigns the file object to the variable "file".

The code then uses a "for" loop to iterate over the list of items returned by the "os.listdir" method, which returns a list of all files and directories in the directory specified by "path". For each item in the list, the code writes the name of the item to the file object using the "write" method, followed by a newline character to create a new line in the file.

After the loop, the code closes the file using the "close" method.

So, in essence, the code is trying to create a simple report of all the files in the directory specified by "path". It does this by iterating over all the files and directories in that directory using the "os.listdir" method, and writing the name of each file to a new text file named "simple-report.txt", with each file name on a separate line. 

import os

path = 'c:\\Python38-64\\DLLs'

file = open('simple-report.txt', 'w')

for x in os.listdir(path):
    file.write(path + '\\' + x + '\n')

file.close()

This Python code imports the "os" module.

It assigns a string path 'c:\Python38-64\DLLs' to the variable "path". This variable represents the path of a directory that contains files.

The code then uses the "open" function to create a new text file named "simple-report.txt" in write mode (indicated by the 'w' argument) and assigns the file object to the variable "file".

The code then uses a "for" loop to iterate over the list of items returned by the "os.listdir" method, which returns a list of all files and directories in the directory specified by "path". For each item in the list, the code writes the full path of the item to the file object using the "write" method, by concatenating the "path" variable with the file name, separated by a backslash, followed by a newline character to create a new line in the file.

After the loop, the code closes the file using the "close" method.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...