【问题标题】:How do I write to a file with spaces and special characters in file name?如何写入文件名中包含空格和特殊字符的文件?
【发布时间】:2021-01-19 16:19:12
【问题描述】:

我正在尝试写入一个名为

的文件
data/STO: INVE-B-TIME_SERIES_DAILY_ADJUSTED-1.csv

在 windows 上使用以下 python 代码

overwrite = "w"  # or write new

f = open(OutputPath(copyNr), overwrite)
f.write(response.content.decode('utf-8'))
f.close()

print(f"Wrote to file: {OutputPath(copyNr)}")

控制台中的输出是正确的,但是写入的文件只产生data/STO,因此路径似乎被剪裁了。我尝试使用 SO answer 中的方法来转义字符,但这给了我以下文件名的 invalid_argument 异常:

data/STO\\:\\ INVE-B-TIME_SERIES_DAILY_ADJUSTED-1.csv

当我删除空间时,我得到了同样的错误,它似乎仍然剪辑在:。如何在文件名中包含此类字符?

【问题讨论】:

  • Windows 不允许在文件名中使用冒号。你做不到。
  • 哦,原来如此!

标签: python file fwrite


【解决方案1】:

你不能。冒号只能在volumeseperator上使用——任何其他地方都是非法的。

允许:

d:/somedir/somefile.txt

非法:

./some:dir/somefile.txt

作为分隔符,您可以使用 '\\' 或 '/' - 两者都应该被理解。

这不是python的限制,而是操作系统的限制。

参见 f.e. What characters are forbidden in Windows and Linux directory names?

【讨论】:

    【解决方案2】:

    Windows API 不允许文件名中有冒号,它是为驱动器号保留的,使用不同的符号。

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 1970-01-01
      • 2018-05-22
      • 2022-11-10
      • 2021-12-08
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      相关资源
      最近更新 更多