Reputation: 53
I am trying to get a python script to read a text file that has a list of names in it and create folders based on those names. For example, if the text file has "john_doe" and "jane_doe" in it, the script should create two folders. One called "john_doe" and one called "jane_doe".
When I run my script, I get the error WindowsError: [Error 123] The filename, directory name, or colume label syntax is incorrect: ",open file 'names.txt', mode 'r' at 0X00000000025E6300>"
Here's the script that I'm running:
import os
with open('names.txt') as x:
for line in x:
line = line.strip()
os.mkdir(str(x))
I think that it's more of a Windows problem (hence the WindowsError), but I'm not sure how to get around it. Any tips?
Upvotes: 1
Views: 4396
Reputation: 101
# My solution from above...
# Trying to create folders from a file
# By Rob Thomas
# 16/3/2019 Ver 2.0
import os,sys
# Change to correct folder to create files in
# Just copy from Windows Explorer, then add in the extra "\"
os.chdir("R:\\_1 Y9 Yellow")
print(os.getcwd())
right=input("Is this correct? Y/N: ")
if right.lower()!="y":
print("Exiting...")
sys.exit()
try: # Also change to the correct file name
with open('Yellow.txt', "r") as x:
for line in x:
line = line.strip()
os.mkdir(str(line))
x.close()
except OSError:
print ("Creation of the directory failed" )
else:
print ("Successfully created the directory" )
Upvotes: 0
Reputation: 5593
Instead of:
os.mkdir(str(x))
You meant:
os.mkdir(str(line))
You don't even need str()
, since line
is already a str
. (I suspect you only added it because os.mkdir(x)
was giving you an error.)
Your previous code was trying to create several directories, all named something like "<open file 'names.txt', mode 'r' at 0X00000000025E6300>
".
Upvotes: 3
Reputation: 109
You may be catching a problem with special characters and whitespace between the names. Windows doesn't like it when you fail to escape the whitespace between multi-word directory names.
Try (i) reading the lines as Unicode (to avoid special character problems) and then (ii) joining the names with an underscore to avoid whitespace issues:
import os
with open('names.txt', 'rU') as x:
for line in x:
line = line.strip().split()
filename = "_".join([i for i in line])
os.mkdir(filename)
Upvotes: 0
Reputation: 1235
Check the current working directory by:
>>> import os
>>> os.getcwd()
You may find that your program maynot have appropriate permission to make changes on the directory.
Try changing to something else like:
>>> os.chdir("<someAbsolutePath>")
And if you find the program can write/ make changes on another directory, then you may need to change the permissions of the program.
Upvotes: 0