我正在尝试使用open(filename,'x')创建一个文本文件。我已经尝试过x ='a +','w +','w'。我正在使用Windows 10,代码为“在终端中运行python文件”和python 3.8.2
import os
print("cwd",os.getcwd())
scriptpath = os.path.dirname(__file__)
filename = "test.txt" #1
#filename = scriptpath + "/test.txt" #2
#filename = r"C:\Users\harki\Documents\ALGO\ALGO-NPL\test.txt" #3
f = open(filename,'w+')
f.write("test")
f.close()
使用第一个文件名运行:
PS C:\Users\harki\Documents\ALGO\ALGO-NPL> & C:/Users/harki/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py
cwd C:\Users\harki\Documents\ALGO\ALGO-NPL
Traceback (most recent call last):
File "c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py", line 11, in <module>
f = open(filename,'w+')
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
使用第二个文件名运行:
PS C:\Users\harki\Documents\ALGO\ALGO-NPL> & C:/Users/harki/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py
cwd C:\Users\harki\Documents\ALGO\ALGO-NPL
Traceback (most recent call last):
File "c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py", line 11, in <module>
f = open(filename,'w+')
FileNotFoundError: [Errno 2] No such file or directory: 'c:/Users/harki/Documents/ALGO/ALGO-NPL/test.txt'
使用第三个文件名运行:
PS C:\Users\harki\Documents\ALGO\ALGO-NPL> & C:/Users/harki/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py
cwd C:\Users\harki\Documents\ALGO\ALGO-NPL
Traceback (most recent call last):
File "c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py", line 11, in <module>
f = open(filename,'w+')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\harki\\Documents\\ALGO\\ALGO-NPL\\test.txt'
我使用此代码定义文件路径,它对我有用:
filename = os.path.join(dirname(realpath(__file__)), 'folder/name', 'test.txt')
然后,我使用joblib或pickle创建文件。
在您的情况下,它类似于第二个文件名,只需要添加join()
函数