python - 检索两个单独文件夹(目录)中的文件列表。如何将终端中的打印内容打印到新的文本文档中?
问题描述
我有一个函数可以从用户在我的 Tkinter GUI 窗口中选择的两个单独的目录(文件夹)中检索文件列表。两个目录中所有文件的列表都可以在 Visual Studio 代码终端中打印,但是如何从这两个目录中获取文件列表以打印到新的文本文件?
Input_1 = entry_field1.get() #Retrieving what the user inputed into entry field 1.
Input_2 = entry_field2.get() #Retrieving what the user inputed into entry field 2.
file_list_1=os.listdir(Input_1) #Listing the files from directory 1.
file_list_2=os.listdir(Input_2) #Listing the files from directory 2.
print (file_list_1) #Printing the files in the terminal window.
print (file_list_2) #Printing the files in the terminal window.
解决方案
有两种简单的方法可以做到这一点,都使用open()
函数。官方文档在这里:https ://docs.python.org/3/library/functions.html 。
Python 3print()
语句
官方文档:https ://docs.python.org/3/library/functions.html
在 python 3 中,print 语句是一个带有附加参数的函数。这些参数之一在这里很有帮助:file
参数。
要打印到文件:
>>> print('hello', file = open('hello.txt','w'))
传统.write()
功能
官方文档:https ://docs.python.org/3/tutorial/inputoutput.html
write 函数有一个参数:一个字符串。要写入文件,首先open()
是它。
>>> my_File = open('hello.txt', 'w') # the 'w' means that we're in write mode
>>> my_File.write('This is text') # Now we need to close the file
>>> my_File.close()
推荐阅读
- python - 套接字不断返回双字符串值
- javascript - 在按钮单击 Angular 上更新列表
- powershell - 如何使用powershell删除所有临时文件
- mongodb - MongoDB TTL,但要做其他事情
- sql - 如何将 1 列中的值分隔为 count 大于 1 的 2 个单独列。不希望行值在列名中
- f# - 计算表达式中的类型推断错误
- perl - 在 Strawberry Perl 中安装“autovivification”模块时出现问题
- mosquitto - 构建 Mosquitto MQTT 身份验证插件问题
- python - 将数据框转换为嵌套的 json
- mysql - Laravel 删除(违反完整性约束)