【问题标题】:How to store all mp4 files names in an array如何将所有 mp4 文件名存储在数组中
【发布时间】:2021-02-15 07:39:42
【问题描述】:

我想将文件从另一个目录移动到当前目录。我将文件从当前移动到另一个没有问题。但反过来我得到这个错误:

FileNotFoundError: [Errno 2] 没有这样的文件或目录:“'Test''.mp4”

FileNotFoundError: [WinError 2] 找不到文件: "'Test''.mp4" -> ".\'Test''.mp4"

filesMove = os.listdir(os.curdir)
for file in filesMove:
    if '.mp4' in file:
        shutil.move(file, '/Users\caspe\OneDrive\Documents\Övrigt\Kodning\Youtube\Clips')
time.sleep(5)

twitchClipTitle=os.listdir(r"C:\Users\caspe\OneDrive\Documents\Övrigt\Kodning\Youtube\Clips")
print(twitchClipTitle)

filesClips = os.listdir(r"C:\Users\caspe\OneDrive\Documents\Övrigt\Kodning\Youtube\Clips")
for file in filesClips:
    shutil.move(file, os.curdir) #I get the error here

此代码的目的是将所有 mp4 文件的名称保存在一个列表中。有没有更好的办法?

【问题讨论】:

  • file 只是文件名。您需要提供.move() 从当前目录到该文件的相对路径,或该文件的绝对路径,以便它能够找到该文件。只给它文件名使它在当前目录中查找文件。 How to debug small programs. | What is a debugger and how can it help me diagnose problems?
  • 好吧,应该是:shutil.move(r"C:\Users\caspe\OneDrive\Documents\Övrigt\Kodning\Youtube\Clips\" + file, os.curdir) 但我明白了Clips 出现语法错误\
  • 这是因为原始字符串不能以反斜杠结尾。
  • 但是我应该如何获取文件的目录呢?

标签: python arrays python-3.x list file


【解决方案1】:

在对move 的调用中包含目录并使用正斜杠。 Python 会根据 os 翻译正斜杠。

filesMove = os.listdir(os.curdir)
for file in filesMove:
    if '.mp4' in file:
        shutil.move(file, '/Users/caspe/OneDrive/Documents/Övrigt/Kodning/Youtube/Clips')
time.sleep(5)

twitchClipTitle=os.listdir(r"C:/Users/caspe/OneDrive/Documents/Övrigt/Kodning/Youtube/Clips")
print(twitchClipTitle)

fldr = r"C:/Users/caspe/OneDrive/Documents/Övrigt/Kodning/Youtube/Clips/"
filesClips = os.listdir(fldr)
for file in filesClips:
    shutil.move(fldr + file, os.curdir) #I get the error here

【讨论】:

  • 工作就像一个魅力,谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 2013-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多