I want to create a folder named after a specific name. Like in the picture (a folder with only numbers except for .zip).
here is my code.
import os
import glob
import zipfile
import sys
p_dir = './data/'
for file in os.listdir(p_dir):
file_name = file
oldname = str(file_name)
newname1 = file.split('_')[5] '.zip'
newname = str(newname1)
os.rename(os.path.join(p_dir, oldname), os.path.join(p_dir, newname))
os.makedirs(p_dir, newname1)
but error is.. TypeError: an integer is required (got type str) What should I do?
CodePudding user response:
The immediate error is that your makedirs
invocation is wrong. If you pass in two arguments, the second argument should be a number which indicates the permissions of the directory; for example, 0o751
(decimal 489) indicates read write execute (7) for owner, read execute (5) for group, and execute (1) for others. (Conventionally, these numbers are communicated in octal, because they map nicely to one digit per permission.)
However, you are also needlessly converting variables which are already strings to strings, and copying things which don't need to be copied.
It's also not clear why you split on _
; your example image shows no file names with underscores in them, let alone then file names with five or more of them. Per your problem description, I'm guessing you want to look for a .zip
extension and remove it.
Try this:
import os
# import glob # unused
# import zipfile # unused
# import sys # unused
p_dir = './data/'
for file in os.listdir(p_dir):
if file.endswith('.zip'):
newname = file[:-4]
os.makedirs(os.path.join(p_dir, newname))
CodePudding user response:
as per your code
newname1 = file.split('_')[5] '.zip'
newname = str(newname1)
newname1
and newname
are the same
as per your code
os.makedirs(p_dir, newname1)
This is wrong code
You need to write
os.makedirs(os.path.join(p_dir, newname1))
But still you will get an error
There fore you need to remove .zip
for newname1
may be like below
newname1 = file.split('_')[5]
newname = str(newname1) '.zip'
So your final code will look like
import os
import glob
import zipfile
import sys
p_dir = './data/'
for file in os.listdir(p_dir):
file_name = file
oldname = str(file_name)
print(file)
newname1 = file.split('_')[5]
newname = str(newname1) '.zip'
os.rename(os.path.join(p_dir, oldname),
os.path.join(p_dir, newname))
os.makedirs(os.path.join(p_dir, newname1))
But I don't understand the _
split
CodePudding user response:
In os.makedirs(path[, mode])
you can pass two parameters. path
and mode
(optional) and the error you get is because the mode
should be an integer. And the default mode is Oo777
in octal. Therefore you can use the following code to fix your problem.
import os
p_dir = './data'
for file in os.listdir(p_dir):
newname = file[:-4]
os.makedirs(os.path.join(p_dir, newname))
or
import os
p_dir = './data'
for file in os.listdir(p_dir):
newname = file[:-4]
os.makedirs(os.path.join(p_dir, newname), 0o777))