python3创建/打开文件区分大小写的Mac

时间:2016-11-10 09:37:16

标签: python python-3.x file-io case-sensitive

尝试了interneting并检查python3文档,但我似乎无法修复以下内容 - 我可能只是错过了一个标志或其他东西!

我想在本地目录中创建和编辑文件。使用python与区分大小写的文件名:但我有以下行为:

~$ python3
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("file.txt", "w")
>>> f.write("hello\n")
6
>>> f.close()
>>> del f
>>> f = open("File.txt", "w")
>>> f.write("BYE\n")
4
>>> f.close()
>>> del f
>>> quit()
~$ ls
Applications    Downloads       Movies       Public
Cloud           File.txt        Music        intel
Desktop         Jagex           Documents    Library
Documents       Library         Pictures
~$ cat File.txt 
BYE
~$ cat file.txt
cat: file.txt: No such file or directory

有谁知道我的" file.txt" [与' hello \ n']文件已经消失了?

谢谢!

Edit1:我准确地使用OSX Sierra 10.12.1。

1 个答案:

答案 0 :(得分:0)

这不是(直接)与Python相关,而是与OS及其文件系统相关。类Unix(例如Linux和BSD)具有严格区分大小写的文件名:file.txtFile.txt是两个不同的文件。另一方面,在Windows上,如果已存在同名的不区分大小写的版本,则将打开该版本而不是创建新版本。因此,在Windows上,您的代码将重新打开(并因w模式而删除)同一文件。我无法访问Mac,所以我不能说它是否是相同的情况。

但是当您使用Python 3.5时,您可以将x模式用于独占创建模式。在此模式下,如果打开调用将打开现有文件,则会出现错误。

您的代码可能会变成:

~$ python3
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("file.txt", "x")
>>> f.write("hello\n")
6
>>> f.close()
>>> del f
>>> f = open("File.txt", "x") # will eventually raise a IOError...
...