简体   繁体   English

如何在特定驱动器的所有子目录中创建文件?

[英]How to create a file in all subdirectories on a specific drive?

I'd like to create a text file (with contents inside) and have that file copies/created in every subdirectory (folder) on a specific drive, say D with Python. 我想创建一个文本文件(内部包含内容),并在特定驱动器的每个子目录(文件夹)中复制/创建该文件,例如使用Python的D。 Preferably using pre-installed python libraries and not needing to pip install anything. 最好使用预安装的python库,而无需pip安装任何内容。

So the Python 3 script runs from drive C, creates a text file with text inside it and pastes that text file once in every folder on Drive D. I need this to work on Windows. 因此,Python 3脚本从驱动器C运行,创建一个内部带有文本的文本文件,并将该文本文件粘贴到驱动器D的每个文件夹中一次。我需要在Windows上使用它。

create("file.txt", contents "example text")
copy("file.txt" to "D:\*")

Example output 输出示例

Copied file.txt to D:\
Copied file.txt to D:\folder example
Copied file.txt to D:\folder example\subfolder example
Copied file.txt to D:\another folder

You can use os.walk to get all directories. 您可以使用os.walk获取所有目录。 For example, try 例如,尝试

import os
filename = "myfile.txt"
filetext = "mytext"
directories = os.walk("D:")
for directory in directories:
    with open(directory[0]+"\\"+filename, "w") as file:
        file.write(filetext)

This will write filetext in a file myfile.txt in every directory in D: . 这会将filetext写入D:中每个目录中的myfile.txt文件中。

Edit: You might want to add a try statement to this, if you don't have permissions to a certain directory 编辑:如果您没有特定目录的权限,则可能要向其中添加一条try语句

It is called recursive directory traversal 这称为递归目录遍历

https://stackoverflow.com/a/16974952/4088577 https://stackoverflow.com/a/16974952/4088577

Hope this hint will help you. 希望此提示对您有所帮助。

This is the line that interests you. 这是您感兴趣的行。

print((len(path) - 1) * '---', os.path.basename(root)) print((len(path)-1)*'---',os.path.basename(root))

If you want to learn more you could read 如果您想了解更多,可以阅读

https://www.bogotobogo.com/python/python_traversing_directory_tree_recursively_os_walk.php https://www.bogotobogo.com/python/python_traversing_directory_tree_recursively_os_walk.php

Like so using OS lib: 像这样使用OS lib:

from os import listdir
from os.path import isfile

path = "/some/path"

for f in listdir(path):
    if not isfile(path):
        filepath = "{0:s}/dummy.txt".format(path)
        with open(filepath, 'w') as f:
            f.write('Hi there!')

or using glob: 或使用glob:

import glob

path = '/some/path/*/'
paths = glob.glob(path)
filename = "dummy.txt"

for path in paths:
    filepath = "{0:s}{1:s}".format(path, filename)
    with open(filepath, 'w') as f: 
        f.write('Hi there!')

Please Note!: Second solluton will work under Linux OS only (because of glob) 请注意!:Second solluton仅在Linux OS下工作(由于glob)

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

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