我想在程序中执行以下操作:
a)要求用户键入文件夹的名称
b)在我的目录中创建文件夹
c)将文件写入此创建的文件夹
我已经在目录中创建了该文件夹,但是我没有设法将文本写入文件并将其保存在该新文件夹中。我的策略是打开以插入目录的完整路径+存储文件夹名称的变量来打开文件,但没有用。有人可以帮我吗?
final_text=' '.join(l)
final_text=final_text.replace(' ,',',')
#print('\n\n', final_text)
def createFolder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print('Error: Creating directory. '+ directory)
user2=input('\nWrite text to a file? Type "Y" for yes or "N" for no:')
if user2 =='Y':
text_name=input("name your folder. E.g. './texts/': ")
createFolder(text_name)
out_file=open('/Users/nataliaresende/Dropbox/PYTHON/'+text_name,"w")
out_file.write(final_text)
out_file.close()
print('\n\nText named',text_name, 'was written to a file. Check your directory')
else:
print('ok')
答案 0 :(得分:0)
Python的pathlib
库(可从Python 3.4+开始使用)使这种事情成为真正的乐趣:
import pathlib
new_dir_name = input('Directory name: ')
new_dir = pathlib.Path('/Users/nataliaresende/Dropbox/PYTHON/', new_dir_name)
new_dir.mkdir(parents=True, exist_ok=True)
# You have to make a file inside the new directory
new_file = new_dir / 'myfile.txt'
new_file.write_text('Hello file')
答案 1 :(得分:0)
您可以先创建文件夹,然后在该文件夹中创建文件:
import os
user_input = input('\nWrite text to a file? Type "Y" for yes or "N" for no:')
if user_input == 'Y':
folder_name = input('name your folder. E.g. "texts": ')
folder = os.path.join('/Users/nataliaresende/Dropbox/PYTHON/', folder_name)
file_name = '{}.txt'.format(folder_name)
file = os.path.join(folder, file_name)
os.makedirs(folder)
with open(file, 'w') as f:
f.write('Some text')
print('\n\nText named "{}" was written to a file. Check your directory: {}'.format(file_name, folder))
else:
print('OK')