作者gamlty99 (548+9)
看板Python
标题[问题] 目标资料夹下创建新文件
时间Sat Nov 4 11:27:45 2017
大家好
请问要怎麽在目标资料夹下创建文件
目前问题是创建出来的文件会在os.getcwd()目前的工作路径下,而不是资料夹内
如果用os.chdir()改变工作路径到资料夹内
filelist = os.listdir(filename),这行就抓不到资料夹内的文件清单
谢谢
def main():
filename = input('choose filename :')
while True:
filelist = os.listdir(filename)
if filelist:
# 如果清单非空就印出目前的档案目录
for i in filelist:
print('{0:d}:{1:s}'.
format(filelist.index(i)+1,i))
# 提供一个讯息引数给用户,获取一个字串返回值
ans = get_str('[A]dd [D]elete [S]ave [Q]uit ans')
if ans.lower() == 'a':
add_file()
def add_file():
name = get_str('Add item')
try:
file = open(name,'x')
except EnvironmentError:
print('Error')
finally:
file.close()
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 1.34.112.229
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1509766069.A.6F1.html
1F:推 ckc1ark: add_file传filename(资料夹名称) 11/04 13:06
2F:→ ckc1ark: add_file里面用open(os.path.join(filename, name)... 11/04 13:06
3F:→ gamlty99: 感谢! 11/04 15:35