我想知道在python中使用循环时,是否有办法在特定目录中创建10个空文件。我需要创建名为test1.txt、test2.txt的文件,一直到test10.txt。我对python非常陌生,因此非常感谢您在这方面提供的任何帮助。这就是我的工作
def createFiles()
lab3='/home/student/Lab3'
#Before creation of files
dir_list = os.listdir(lab3)
print("List of directories before creating files")
print(dir_list)
print()
with open('test1.text', 'w'):
pass
#After creation of files
dir_list=os.listdir(lab3)
print("Directory and files after file creation: ")
print(dir_list)
以下是如何在一行中完成您想做的事情:
如果您想在文件不存在时创建文件,但不想删除任何已经存在的文件的内容,只需使用
a
而不是w
在python中,它非常简单
F-String in Python
只需将对
open
的调用放入循环中:range
用于生成整数序列;它是开始包含和结束独占的,因此range(1,11)
产生整数1到10。open
中的^{相关问题 更多 >
编程相关推荐