且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Python 中打开作为符号链接的文件

更新时间:2023-11-25 16:25:46

其他地方出了问题.我强烈怀疑您没有从包含 file.txt 的目录中运行它.

Something else has gone wrong. I strongly suspect that you're not running this from the directory that contains file.txt.

我使用的是 Windows 10 和 Python 3.6.

I'm using Windows 10, and Python 3.6.

这里我正在创建一个文件(使用可信赖的记事本).我在文件的第一行中添加了一些文本,并验证它存在于第二行中.

Here I am creating a file (using trusty notepad). I added some text to the file during the first line, and verified that it was present in the second.

cd c:\
notepad test.txt
mklink other.txt test.txt
notepad other.txt

现在转到python...

Now over to python...

f = open("C:\\other.txt")
f.read()

这一切都对我有用.需要更多详细信息才能为您提供帮助,但就目前而言,您的问题无法重现.

This all worked for me. More details will be required in order to assist you, but as it stands your problem is not reproducible.

既然你已经用确切的步骤更新了你的问题,我可以告诉你到底出了什么问题.

Now that you've updated your question with exact steps I can tell you exactly what's going wrong.

但首先 - 尝试在记事本(或其他任何东西)中打开该文件.

But first - try opening that file in notepad (or anything else).

它不会打开 - 而是会出现文件错误.

It won't open - instead it'll give a file error.

这是因为你给它的路径.Windows 使用 \ 作为目录分隔符 - 但您已经使用 / 创建符号链接.此符号链接指向无效的文件名.Python 足够好(跨平台)可以为您转换它 - 但 Windows 没有这样的事情.

This is because of the path you've given it. Windows uses \ for directory seperators - but you've used / to create the symlink. This symlink points to an invalid filename. Python is nice enough (being crossplatform) to convert it for you - but windows does no such thing.

再次尝试您的说明 - 但这次使用 mklink FileA.txt "..\FileA.txt"

Try your instructions again - but this time use mklink FileA.txt "..\FileA.txt"