问题
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.
- Create
FileA.txt
inDirectoryA
which is aboveDirectoryB
- Inside
DirectoryB
, Runmlink FileA.txt "../FileA.txt"
- Run a Python script which attempts to read and print from the
FileA.txt
link inDirectoryB
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