简体   繁体   中英

How do I find directory of the Python running script from inside the script?

How do I find the directory of the running Python script from inside Python [3.3]? I have tried what was suggested at: How can I find script's directory with Python? , but I get "Invalid syntax" and directed to "os" (And I did import os).

The closest I have got to the answer is: sys.argv[0] , but that still includes the file name, so I cannot use it. Is there any other way?

NOTE: I am fairly new to Python.

Here is some code I have made so far (the part where it says rundir = sys.argv[0] is where the suggested code will go):

import pygame
from pygame.locals import *
import os, sys
import time
pygame.init()

import statuscheck
print("Completed program status check.")

import mods.modlist
print("Loaded all mods..")

print("Completed loading")

sys.dont_write_bytecode = True

rundir = sys.argv[0]

print("Running from" + rundir)

To get the directory that contains the module you are running:

import os
path = os.path.dirname(os.path.realpath(__file__))

Or if you want the directory from which the script was invoked:

import os
path = os.getcwd()

From the docs :

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file.

Depending on how the script is called, this may be a relative path from os.getcwd() , so os.path.realpath(__file__) will convert this to an absolute path (or do nothing is the __file__ is already an absolute path). os.path.dirname() will then return the full directory by stripping off the filename.

Try this:

import os
os.path.dirname(__file__)

__file__ gets the name of the file you are in. The dirname function gets the directory that the file is in.

The syntax error probably had to do with the print statement. In python 3.x

print "hi"

is invalid. Print is now a function.

print("hi")

works. You need the parentheses.

This should work:

import os,sys
print(os.path.dirname(os.path.realpath(sys.argv[0])))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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