简体   繁体   中英

Python file path in Windows

I am using Windows 10. I have this code,

script_dir = os.path.dirname(__file__)
temp = cs(os.path.join(script_dir+"first.txt"), 
    os.path.join(script_dir+"second.text"), 
    os.path.join(script_dir+"third.txt"))

It executes in git bash, but it throws an error in powershell and cmd. How can I fix this code, so that I can execute this code in anywhere?

============================================================
Edit:
it says, it cannot find .first.txt and following files. It also throws this error, DLL load failed: The specified module could not be found.
============================================================
Edit2:
cs is a class I created.

class cs:
    info = {}
    result = {}
    def __init__(self, first, second, third, output=None):
        self.output = ""
        self.first = first
        self.second = second
        self.third = third
    def decrypt(self):
        pass

I don't know why it works in git bash, but not in powershell and cmd

The correct code is

script_dir = os.path.dirname(__file__)
temp = cs(os.path.join(script_dir, "first.txt"), 
    os.path.join(script_dir, "second.text"), 
    os.path.join(script_dir, "third.txt"))

What you are doing wrong, is adding "first.txt" etc to script_dir , and passing that to os.path.join . os.path.join , however, takes multiple arguments (any number of arguments) and joins them together in the correct way. What your code did, is add those strings together, making: script_dirfirst.txt , which would explain why it couldn't find the file.

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