[Python] Small function of enumerating folders and files

One day at work, I need to organize the file names in the folder into Excel, as shown in the figure below. It is too time-consuming and laborious to copy and paste the names one by one. However, I am not familiar with Excel functions, so I don’t know if it has convenient commands.

cda6a50c10992c74dd6c09cb29edca03.jpeg

In this case, think about writing two sentences of code in Python or easy language. Let's use py this time, and the code is attached at the end of the article.

a98036200ef27f72bd2bfc327e0b5901.png

After pasting the file path, there will be a crackling output, and all the file names will be saved in the txt file in an instant:

6b15c033a8e04886be2979cd6af121ee.png

Open Excel again, paste the content in the txt file, and sort the data into columns, because these file names are in the form of code [space] names, and need to be extracted separately.

2641b200bac33eaebf150c6405ee9b0c.png

Choose Delimiter, and choose Space:

a578a0f43c062e11895230bd5c0ea44a.png

040ce87675dbb631094a4681a8a795e6.png

final result:

9ce67d5c1bb608752bce75961a6f8f1f.png

Code :

import os,random
print("欢迎关注微信公众号:偶尔敲代码")
#readline.parse_and_bind("control-v: paste")#解决控制台无法粘贴的问题
dir = input('输入要枚举的文件夹路径:')
list_data = os.listdir(dir)
file = open(dir + '/123.txt', 'w+')


for name in list_data:
        file.write(name + '\n')
        print(name)
file.close()
print("结果保存路径:" + dir + '\123.txt, 数量:' + str(len(list_data)) + "个")
input('按任意键结束')

For these 67 files, although typing code + debugging may not be faster than manually copying and pasting one by one, but as long as the work is repetitive, the value of this code can be reflected.

Amateur writing and writing code may not be as good as a professional programmer, but at least it can exercise logical thinking and prevent Alzheimer's, haha. I have also been thinking about writing two lines of code, and I can't use them all to write scripts. Although learning Python is indeed because of the Qinglong panel, but now that I am getting started, I need to study more serious things that solve practical problems. I also want to create a collection and include practical articles or gadgets in it, so that I can better understand what I have written and what it can be used for.

Friends who are interested or confused in this area, let's encourage each other. May Day is here, besides going out and crowding people, you can learn something at home.

- End -

More exciting articles

Click on the business card below to follow【Occasionally type code】

Light up the little flowers to let more people know

Guess you like

Origin blog.csdn.net/a18065597272/article/details/130437441