Reputation: 11
I try to write something in Python 2.7 to create many directories from a .txt file. So far I got this:
import os
path = '.'
system_name = open('systems.txt')
system = system_name.readline()
while system:
print(system)
for system in system:
os.mkdir(os.path.join(path,(system)))
system_name.close()
My input file looks like this:
BaO_Fm-3m_26961_RPBE
BaZrO3_Pm-3m_90049_RPBE
BeO_P63mc_61181_RPBE
Bi2O3_P211c_15072_RPBE
CaMgSi2O6_C12c1_30522_RPBE
...
The problem is that I get many folders but all of them are created letter by letter from the first line and not row by row like I intended.
Than you very much for the kind help and enjoy your day,
Ingo
Upvotes: 1
Views: 383
Reputation: 685
import os
path = '.'
lines = tuple(open('systems.txt', 'r'))
print lines
for system in lines:
os.mkdir(os.path.join(path,(system)))
Upvotes: 0
Reputation: 77
Try to open files with the with statement for more safety. Also, you can iterate on a file with a for loop, which will give you all the lines.
with open('systems.txt') as system_name:
for line in system_name:
print(line)
line = line.strip() #to remove things like '\n'
os.mkdir(os.path.join(path, line))
Upvotes: 1
Reputation: 1928
The problem is that you're iterating over a first line instead of list of lines so you create folders for each character from the first line. Use readlines
instead.
with open('systems.txt') as f:
lines = f.readlines()
for file_name in lines:
os.mkdir(os.path.join(path, file_name))
Upvotes: 1
Reputation: 181735
readline()
reads one line. Then you iterate over that line using for system in system
, so you get each character in turn.
Conveniently, files in Python can already be iterated over line by line:
system_name = open('systems.txt')
for system in system_name:
os.mkdir(os.path.join(path, system))
system_name.close()
You could also look into the with
construct to make this exception-safe.
Upvotes: 1