我使用os.mkdir()创建了一个新目录'Student'和'Faculty'。我需要将学生文件保存在“学生”文件夹中,并将员工详细信息保存在“学院”文件夹中。如何手动执行?我需要设置一个路径,将文件写入到Student和Faculty文件夹中。
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)
答案 0 :(得分:0)
尝试使用os.chdir('complete_path_you_want_to_switch')
将当前目录更改为您想要的目录,否则会阻塞并尝试在其中写入文件。
答案 1 :(得分:0)
使用os.getcwd
到当前工作目录
path=os.getcwd();
然后将目录,输出文件追加到该路径
f=open(path+stuDir+outfile, 'w')
答案 2 :(得分:0)
如果要使用相对路径,只需使用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()
答案 3 :(得分:0)
对于Python 3.6 +,pathlib中提供了一个新的Path对象,可以根据您的情况像这样工作。在此示例中,无需设置路径。假定stuDir和facDir是本地路径,之后它们可以使用.absolute()为您提供完整路径,例如facDir.absolute()
from pathlib import Path
outfile = "somefilenamehere.csv"
stuDir = Path('StudentDetails')
facDir.mkdir(exist_ok=True)
facDir = Path('FacultyDetails')
facDir.mkdir(exist_ok=True)
if(tempNo[0]=='E'):
#now outfile is a path
outfile = facDir/outfile
elif(tempNo[0]=='R'):
outfile = facDir/outfile
#try out this last line as I can't verify that it works without some data which was not provided.
outfile.write_lines([csv.writer(j) for j in tempList2 if temp==j[0]]