繁体   English   中英

Python如何在没有完整路径的情况下打开文件

[英]Python how to open a file without having the full path

所以我想在没有完整路径的情况下从文件中读取内容,我该怎么做? 我当前的代码

import json

file1= 'C:\\Users\\klaus\\OneDrive\\Desktop\\Script\\Mediamarktp.json'

with open(file1, 'r') as handle:
    json_out = json.load(handle)

profile_name = ['Profile1']

data = [x for x in json_out if x['profilename'] in profile_name]
email = (data[0]['email'])
password = (data[0]['password'])
website = (data[0]['website'])
precart = (data[0]['precart']=='True')
profilename1 = (data[0]['profilename1'])
proxy = (data[0]['proxy']=='True')

print(email)
print(password)
print(precart)

file1 目前是 = 'C:\\Users\\klaus\\OneDrive\\Desktop\\Script\\Mediamarktp.json' 但我希望我的脚本打开它只需要寻找 = '\\Script\\Mediamarktp.json'

file1 = 'C:\\*\\Script\\Mediamarktp.json'

我该怎么做?

程序在大多数具有“当前工作目录”概念的操作系统中运行。 因此,当要求代码打开文件时,它可以是完整路径(如 Windows 中以“C:”开头的路径),也可以是“相对路径”,这取决于文件相对于当前工作目录的位置.

如果您从命令提示符运行程序,您可以cd到正确的父目录( C:\\\\Users\\\\klaus\\\\OneDrive\\\\Desktop\\\\ ),然后仅使用相对路径访问该文件。 但它不能以\\\\开头!

file1= 'Script\\Mediamarktp.json'

这与glob模块配合得很好。

import glob
myFiles = glob.glob(r'C:\**\Mediamarktp.json, , recursive=True)

如果您不使用recursive=True它不会在子文件夹中搜索。 但这实际上会找到具有该名称的所有文件并搜索驱动器上的所有目录。 因此会很慢,这样做是不合理的。 如果您想使用glob将其限制为更合理的起始路径。

另一种方法是将工作目录设置为包含文件的路径

import os
os.chdir(myPath)

有了这个,你可以直接用它的名字打开文件。 您还可以使用脚本启动工作目录中的相对路径。 如果您不确定它是什么,您可以使用

print("Current Working Directory " , os.getcwd())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM