【问题标题】:Python - Why is "Pathlib.Path.touch()" appending a "?" to the filenamePython - 为什么“Pathlib.Path.touch()”附加一个“?”到文件名
【发布时间】:2021-11-08 12:42:49
【问题描述】:

我有一个名为“mp3.txt”的文件,内容如下:

1.mp3
2.mp3
3.mp3
4.mp3
5.mp3

读取“mp3.txt”的Python代码,并为每一行创建一个新文件:

from pathlib import Path

with open("mp3.txt", "r") as file:
    for line in file.readlines():
        Path(line).touch()

结果:

1.mp3?         3.mp3?         5.mp3?         
2.mp3?         4.mp3?      

我只有在读取文件时才会遇到这种情况。如果我从 list() 而不是像这样的文件做同样的事情:

from pathlib import Path

l = ["1.mp3", "2.mp3", "3.mp3", "4.mp3", "5.mp3"]

for i in l:
    Path(i).touch()

输出看起来不错:

1.mp3   2.mp3   3.mp3   4.mp3   5.mp3

是的,我确实尝试将文件的内容附加到 list() 中:

from pathlib import Path

l = []

with open("mp3.txt", "r") as file:
    for line in file.readlines():
        l.append(line)

for i in l:
    Path(i).touch()

和“?”仍然被附加在文件名中。文档没有关于这种行为的任何内容。

【问题讨论】:

  • 它是您在文件mp3.txt 中的“新行”。看我的回答。

标签: python file touch filenames pathlib


【解决方案1】:

Strip 字符串(文件名)。每个文件名后面的“新行”导致? 成为Path 创建的文件的一部分

from pathlib import Path

with open("mp3.txt", "r") as file:
    file_names = [line.strip() for line in file.readlines()]
    for file_name in file_names:
        Path(file_name).touch()

【讨论】:

    【解决方案2】:

    根据答案,我想出了这个:

    from pathlib import Path
    
    with open("mp3.txt", "r") as file:
        for line in file.readlines():
            new = line.strip()
            Path(new).touch()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 2012-08-12
      相关资源
      最近更新 更多