python 一个简单的python3程序,用于将给定目录中的文件和文件夹列表写入tesxt文件。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 一个简单的python3程序,用于将给定目录中的文件和文件夹列表写入tesxt文件。相关的知识,希望对你有一定的参考价值。

__author__ = 'payload'

from os import listdir

# this program copies the file/folder names in a given directory to a text file.

# start the program
proceed = True

while proceed is True:

	file_list = []
	file_name_first = input("Enter the output file name")
	file_name = file_name_first + '.txt'
	# print("Started to write in the " + file_name)
	file = open(file_name, 'w')

	write_cycle = True

	while write_cycle is True:
		dir_okay = False

		# gets the directory
		while dir_okay is False:
			print("Enter the path to be recorded:")
			path = input("eg. /home/user/ or 'q' to quit entering:")

			if path == 'q':
				write_cycle = False
				break
			else:

				# opens the directory
				try:
					file_list = listdir(path)
					dir_okay = True

					# process the directory
					file_list.sort()
					disk_no = input("Enter the disk number!")
					directory_name = input("Enter the directory/disk name:")
					# print('wrote the file ' + directory_name + str(file_list))
					file.write(disk_no + "\t")
					file.write(directory_name + "\t")

					for directory in file_list:
						file.write(" \t\t\t" + directory + "\n")

				except FileExistsError:
					print('Error: The file already exist!')
					dir_okay = False

				except FileNotFoundError:
					print('Error: File Not Found!')
					dir_okay = False

				except InterruptedError:
					print('Error: Operation Interrupted!!')
					dir_okay = False

				except PermissionError:
					print('Error: Permission denied!')
					dir_okay = False

				except TimeoutError:
					print('Error: Operation timed out!')
					dir_okay = False

	file.close()
	print('The task is completed! do you want to start another task?')
	confirm = input("Enter 'no' to quit,  'yes' to start a new tas!")

	# exit the program
	if confirm == 'yes':
		print('Now starting a new task!')
		proceed = True
		continue
	else:
		print('Re enter the files now!!')
		break

print("Quitting the program . . . ")

以上是关于python 一个简单的python3程序,用于将给定目录中的文件和文件夹列表写入tesxt文件。的主要内容,如果未能解决你的问题,请参考以下文章

如何将python2的代码升级到python3

python第一个程序出错

Python3的tkinter写一个简单的小程序

python3 中,一个语句可以分成多行书写吗

用于 Qt 4、Python 3 的 matplotlib 小部件

python3的一个简单爬虫