what I want to do with my code is:
With my code, I created the folder, but it does not write the text to a file inside this new folder. Can anyone help me with that?
The error I get is below:
Traceback (most recent call last): File "/Users/nataliaresende/Dropbox/PYTHON/word_concatenator_final.py", line 390, in menu() File "/Users/nataliaresende/Dropbox/PYTHON/word_concatenator_final.py", line 384, in menu remove_paratext() File "/Users/nataliaresende/Dropbox/PYTHON/word_concatenator_final.py", line 342, in remove_paratext with open(file, 'w') as f: IsADirectoryError: [Errno 21] Is a directory: '/Users/nataliaresende/Dropbox/PYTHON/no_tag/chap1.txt
My Code:
file_to_open=input('Enter your file name: ')
with open(file_to_open) as t:
text=t.read()
pat=re.compile(r'(\[@PARAST@\]).+?(\[@PARAFN@\])')
s = re.sub(pat, '', text)
user=input('\n\nCreate a folder?| Y/N: ')
if user == 'Y':
folder_path=Path(input('\n\nEnter your folder path: '))
folder_name=input('\n\nName your folder: ')
file_name=input('\n\nName your file: ')
file_path=os.path.join(folder_path, folder_name)
os.makedirs(file_path)
file=os.path.join(file_path,file_name)
with open(file, 'w') as f:
f.write(s)
print('\n\nText named', file_name +'.txt', 'written to a file. Check folder named',folder_name, 'in your directory')
else:
no_tags1=open(file_to_open + 'no_tags.txt', 'w')
no_tags1.write(s)
no_tags1.close()
I expect to create write the text stored in a variable to a file inside a folder created and named by the user.
The problems seems to be that the new directory that you try to create already exist.
You can see that with the line :
in makedirs mkdir(name, mode)
FileExistsError: [Errno 17] File exists: '/Users/nataliaresende/Dropbox/PYTHON/no_tags'
To solve this just add a try except around the line os.makedirs(file_path)
try:
os.makedirs(file_path)
except FileExistsError:
print("Directory already exists")
#Do something else or just pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.