Opening a file which is a symlink in Python

筅森魡賤 提交于 2019-12-20 03:05:56

问题


I have some python code that opens a file to read it like so...

with open("file.txt") as f:
    print(f.read())

On MacOS, if file.txt is a symlink - Python will follow the symlink and read the target file. However, on Windows it does not do this - how can I achieve this?

(Using Python version 3.6.5 and Windows 10) Steps to reproduce.

  1. Create FileA.txt in DirectoryA which is above DirectoryB
  2. Inside DirectoryB, Run mlink FileA.txt "../FileA.txt"
  3. Run a Python script which attempts to read and print from the FileA.txt link in DirectoryB

Expected Behaviour:

The contents of FileA.txt inside DirectoryA should be printed

Actual Behaviour:

OSError: [Errno 22] Invalid argument: 'FileA.txt'


回答1:


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

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

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.

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.

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




回答2:


I don’t do MS Windows. But this might help: http://winshell.readthedocs.io/en/latest/shortcuts.html

Does your version of MS Windows actually support symlinks? Or are you dealing with these “shortcuts” (Shell links)? Does it actually have a .lnk extension?



来源:https://stackoverflow.com/questions/50321207/opening-a-file-which-is-a-symlink-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!