在循环python中创建多个空文件

2024-10-02 22:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道在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)    

Tags: 文件of目录txtosdirfileslist
3条回答

以下是如何在一行中完成您想做的事情:

for i in range(10): open(f'/tmp/test{i+1}.text', 'w').close()

如果您想在文件不存在时创建文件,但不想删除任何已经存在的文件的内容,只需使用a而不是w

在python中,它非常简单

#counting starts from 0
for i in range(10):
    i+=1
    with open(f"test{i}.txt","w"):
        pass

F-String in Python

只需将对open的调用放入循环中:

for i in range(1, 11):
    with open(f'test{i}.txt', 'w'):
        pass

range用于生成整数序列;它是开始包含和结束独占的,因此range(1,11)产生整数1到10。open中的^{} string提供了一种在字符串中放置变量的好方法

相关问题 更多 >