【问题标题】:Is there a way to change your cwd in Python using a file as an input?有没有办法使用文件作为输入来更改 Python 中的 cwd?
【发布时间】:2020-03-25 07:13:40
【问题描述】:

我有一个 Python 程序,我在其中计算不同目录中的文件数,但我想知道是否可以使用包含不同目录位置列表的文本文件来更改程序中的 cwd?

输入:将是具有不同文件夹位置的文本文件,其中包含各种文件。

我将我的程序设置为返回给定文件夹位置中的文件总数,并将数量返回到一个计数文本文件,该文件将位于调用程序的每个文件夹中。

【问题讨论】:

  • 您能详细说明一下吗?什么是输入输出?
  • chdir 接受 str 参数。 str 来自哪里并不重要。

标签: python file input


【解决方案1】:

您可以在 Python 中使用os 模块。

import os

# dirs will store the list of directories, can be populated from your text file
dirs = []

text_file = open(your_text_file, "r")
for dir in text_file.readlines():
    dirs.append(dir)

#Now simply loop over dirs list
for directory in dirs:
    # Change directory
    os.chdir(directory)

    # Print cwd
    print(os.getcwd())

    # Print number of files in cwd
    print(len([name for name in os.listdir(directory)
               if os.path.isfile(os.path.join(directory, name))]))

【讨论】:

    【解决方案2】:

    是的。

    start_dir = os.getcwd()
    indexfile = open(dir_index_file, "r")
    for targetdir in indexfile.readlines():
        os.chdir(targetdir)
        # Do your stuff here
    
    os.chdir(start_dir)
    

    请记住,如果您的程序在中途死机,它会将您留在与开始时不同的工作目录中,这会使用户感到困惑并且有时可能很危险(尤其是如果他们没有注意到它已经发生并开始尝试删除他们期望在那里的文件 - 他们可能会得到错误的文件)。您可能需要考虑是否有一种方法可以在不更改工作目录的情况下实现您想要的。

    编辑:

    建议后者,而不是更改目录使用os.listdir() 来获取感兴趣目录中的文件:

    import os
    start_dir = os.getcwd()
    indexfile = open(dir_index_file, "r")
    for targetdir in indexfile.readlines():
        contents = os.listdir(targetdir)
        numfiles = len(contents)
        countfile = open(os.path.join(targetdir, "count.txt"), "w")
        countfile.write(str(numfiles))
        countfile.close()
    

    请注意,这将计算文件和目录,而不仅仅是文件。如果你只想要文件,那么你必须通过os.listdir返回的列表检查每个项目是否是使用os.path.isfile()的文件

    【讨论】:

    • “如果你的程序在中途死掉,它会让你进入一个与你开始的工作目录不同的工作目录”。这不是真的,每个进程都有自己的当前目录。例如运行sh -c 'cd /etc; ls passwd'python -c 'import os; os.chdir("/etc")',你会注意到你的shell 的当前目录没有改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2021-07-16
    相关资源
    最近更新 更多