遇到 python 在open file for write 時, 會顯示錯誤:
FileNotFoundError: [Errno 2] No such file or directory: ''
解法: Specifying an absolute path to the file
import os
current_directory = os.getcwd()
或
working_dir = os.path.dirname(os.path.realpath(__file__))
target_path = os.path.join(working_dir, your_filename)
You’ll see this error if the directory containing the file you’re trying to open does not exist, even when trying to open the file in w
mode.
Since you’re opening the file with a relative path, it’s possible that you’re confused about exactly what that directory is. Try putting a quick print to check:
import os
curpath = os.path.abspath(os.curdir)
packet_file = "%s/%s/%s/%s.mol2" % ("dir", "dir2", "dir3", "some_file")
print "Current path is: %s" % (curpath)
print "Trying to open: %s" % (os.path.join(curpath, packet_file))
packetFile = open(packet_file, "w")