如何在运行时使用python设置保存文件的路径?

2024-05-15 17:39:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个新的目录'学生'和'教员'使用操作系统mkdir(). 我需要保存学生档案在'学生'文件夹和员工详细信息在'教员'文件夹。如何手动执行?我需要设置一个路径将文件写入学生和教员文件夹。你知道吗

import os
stuDir = 'StudentDetails'
os.mkdir(stuDir)
facDir = 'FacultyDetails'
os.mkdir(facDir)
if(tempNo[0]=='E'):
 #I need to set a path to 'Faculty'folder
elif(tempNo[0]=='R'):
 #I need to set a path to 'Student'folder
f=open(outfile, 'w')
for j in tempList2:
  if(temp==j[0]):
   writer = csv.writer(f)
   writer.writerow(j)

Tags: topath文件夹ifosfolderneed学生
3条回答

尝试使用os.chdir('complete_path_you_want_to_switch')if else块将当前目录更改为所需的目录,然后尝试在那里写入文件。你知道吗

os.chdir()

对当前工作目录使用os.getcwd

path=os.getcwd();

然后将目录、outfile附加到该路径

f=open(path+stuDir+outfile, 'w')

如果需要相对路径,只需使用os.path.dirname(__file__),然后使用os.path.join()连接路径。要在刚创建的文件夹中写入文件,只需使用相同的文件路径,如下例所示:

import os
stuDir = 'StudentDetails'
stuDir_filepath = os.path.join(os.path.dirname(__file__), stuDir)
os.mkdir(stuDir_filepath)

facDir = 'FacultyDetails'
facDir_filepath = os.path.join(os.path.dirname(__file__), facDir)
os.mkdir(facDir_filepath)

name_of_file = "name_file"
file_path= os.path.join(facDir_filepath, name_of_file+".txt")         
file1 = open(file_path, "w")
toFile = "Some Text here"
file1.write(toFile)
file1.close()

相关问题 更多 >