将文件位置传递给python

Jaf*_*els 7 python

我对 Linux 和 Ubuntu 完全陌生。

我已经在 Windows 中编写了 python 代码并想在 Ubuntu 中运行它。它使用文本文件进行输入。Windows 中的“文件路径”如下所示

c:user\documents\python\file.txt
Run Code Online (Sandbox Code Playgroud)

Ubuntu的位置是如何写的?

Tak*_*kat 25

我们应该使用模块 os中的路径操作,而不是在 Python 脚本中硬编码路径。

os.path.expanduser( path )路径扩展到用户的主目录
os.path.join( path1 ,*path2*,...)用适当的分隔符连接路径元素
os.sep给出操作系统相关的路径分隔符(/对于Linux/Unix,\对于 Windows)
os.getcwd()给出当前工作目录
os.path.abspath(path)给出给定路径的依赖于操作系统的绝对路径

例子:

>>>import os
>>>path = os.path.join(os.path.expanduser('~'), 'documents', 'python', 'file.txt')
>>>print (path)
Run Code Online (Sandbox Code Playgroud)

结果

/home/user/documents/python/file.txt ## when on Ubuntu
C:\Users\user\documents\python\file.txt ## when running Windows
Run Code Online (Sandbox Code Playgroud)