[英]Create new txt file inside directory PYTHON SCRIPT
I wanted to create a new txt file inside each directory each loop.我想在每个循环的每个目录中创建一个新的 txt 文件。
import os
path='/home/linux/Desktop'
os.chdir(path)
for i in range(10):
NewDir = 'File' + str(i)
os.makedirs(NewDir)
how can I put txt file in each created directory?如何将txt文件放在每个创建的目录中? thankyou谢谢
The typical way to create a new file is the following:创建新文件的典型方法如下:
open(filepath, 'a').close()
The append ( 'a'
) mode will note overwrite existing files and create a new empty file if none exist.附加 ( 'a'
) 模式将注意覆盖现有文件并在不存在时创建一个新的空文件。 If you want to overwrite existing files, you can use the 'w'
mode.如果要覆盖现有文件,可以使用'w'
模式。
The file creation is handled at opening.文件创建在打开时处理。 In your for loop, just add this:在您的 for 循环中,只需添加以下内容:
open(NewDir + "/your_file_name.txt", 'w').close()
EDIT: added "/" to file name编辑:在文件名中添加了“/”
If you are using os.mkdir
it is going to create a new folder
named as File0
..., File9
.如果您使用os.mkdir
它将创建一个名为File0
..., File9
的new folder
。 You can try this to create file:你可以试试这个来创建文件:
import os
path='/home/linux/Desktop'
os.chdir(path)
for i in range(10):
open(f"File{i}.txt","w").close()
This is going to create files under /home/linux/Desktop
named as File0
, File1
,....., File9
.这是怎么回事下创建文件/home/linux/Desktop
命名为File0
, File1
,......, File9
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.