简体   繁体   English

在目录 PYTHON SCRIPT 中创建新的 txt 文件

[英]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'模式。

You can use pathlib to simplify file/directory manipulations.您可以使用pathlib来简化文件/目录操作。

from pathlib import Path

path = Path('/home/linux/Desktop')
for i in range(10):
    new_dir = path / f'File{i}'
    new_dir.mkdir()
    (new_dir / 'some.txt').write_text('Some desired content')

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 ..., File9new 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命名为File0File1 ,......, File9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM