在Python中使用“with open”将内容写入另一个目录

4

我想要做以下几件事:

1) 要求用户输入他们希望列出目录的文件路径。 2) 将此文件路径作为列表输入到文本文件中,该文本文件位于用户输入的目录中而非当前目录。

我已经接近成功,但最后一步是我似乎无法将文件保存到用户输入的目录,只能保存到当前目录。我在下面列出了当前代码(对于当前目录有效)。我尝试了各种变化来尝试将其保存到用户输入的目录,但都没有成功 - 任何帮助将不胜感激。

以下是代码:

import os

filenames = os.path.join(input('Please enter your file path: '))
with open ("files.txt", "w") as a:
    for path, subdirs, files in os.walk(str(filenames)):
       for filename in files:
         f = os.path.join(path, filename)
         a.write(str(f) + os.linesep)
3个回答

0

你需要修改 with open ("files.txt", "w") as a: 这句话不仅包含文件名,还要包含路径。这就是你应该使用 os.path.join() 的地方。最好先使用 os.path.exists(filepath) 检查用户输入的文件是否存在。

os.path.join(input(...)) 对于 input 来说并没有什么意义,因为它只返回一个单独的 str,所以没有什么可以连接的东西。

import os

filepath = input('Please enter your file path: ')
if os.path.exists(filepath):
    with open (os.path.join(filepath, "files.txt"), "w") as a:
        for path, subdirs, files in os.walk(filepath):
            for filename in files:
                f = os.path.join(path, filename)
                a.write(f + os.linesep)

请注意,您的文件列表将始终包括一个files.txt条目,因为在{{link1:os.walk()}}获取文件列表之前,该文件已经被创建。
正如ShadowRanger所指出的那样,这种LBYL(先看后跳)方法是不安全的,因为存在检查可能会通过,尽管在进程运行时文件系统稍后发生了更改,导致异常。
提到的EAFP(宁愿请求原谅,而不是事先获得许可)方法将使用一个try... except块来处理所有错误。
这种方法可能看起来像这样:
import os

filepath = input('Please enter your file path: ')
try:
    with open (os.path.join(filepath, "files.txt"), "w") as a:
        for path, subdirs, files in os.walk(filepath):
            for filename in files:
                f = os.path.join(path, filename)
                a.write(f + os.linesep)
except:
    print("Could not generate directory listing file.")

你应该通过捕获具体的异常来进一步完善它。如果在try块中的代码越多,那么也会抓住并压制更多与目录读取和文件写入无关的错误。


这并没有将文件放在OP指定的目录中,它使用了LBYL设计而不是EAFP(所以它是有风险但没有真正收益的),而且它甚至无法运行,因为你使用了一个不存在的名称。 - ShadowRanger
感谢你的热心建议,@ShadowRanger,我已经更新了我的帖子。 - Christian König

0

进入所选目录,然后进行操作。

额外提示:在 Python 2 中使用 raw_input 来避免特殊字符错误,例如 :\ (在 Python 3 中只需使用 input)。

import os

filenames = raw_input('Please enter your file path: ')
if not os.path.exists(filenames):
    print 'BAD PATH'
    return
os.chdir(filenames)
with open ("files.txt", "w") as a:
    for path, subdirs, files in os.walk('.'):
        for filename in files:
            f = os.path.join(path, filename)
            a.write(str(f) + os.linesep)

raw_input 在 Python 2.x 中需要使用,在 Python 3.x 中可以使用 input。此外,据我所知,“files.txt” 应该保存在列出的同一文件夹中。您的代码没有这样做。最初提供 os.walk 的方法已经在正确的路径中列出了文件。 - Christian König
哦,你是对的!那我们可以在打开文件之前直接移动到最终目录。关于Python版本,我会在我的答案中指出。 - Vanojx1

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接