在 Python 中打开作为符号链接的文件 [英] Opening a file which is a symlink in Python

查看:27
本文介绍了在 Python 中打开作为符号链接的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 python 代码可以打开一个文件来读取它......

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

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

在 MacOS 上,如果 file.txt 是一个符号链接 - Python 将跟随符号链接并读取目标文件.但是,在 Windows 上它不会这样做 - 我怎样才能做到这一点?

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?

(使用 Python 3.6.5 版和 Windows 10)重现步骤.

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

  1. DirectoryB
  2. 之上的DirectoryA中创建FileA.txt
  3. DirectoryB中,运行mlink FileA.txt "../FileA.txt"
  4. 运行一个 Python 脚本,该脚本尝试从 DirectoryB
  5. 中的 FileA.txt 链接读取和打印
  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

预期行为:

应该打印DirectoryA里面FileA.txt的内容

实际行为:

OSError:[Errno 22] 无效参数:'FileA.txt'

推荐答案

其他地方出了问题.我强烈怀疑您没有从包含 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"

这篇关于在 Python 中打开作为符号链接的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆