简体   繁体   中英

read txt file and create folder from single line

I have a list.txt with simple names (for example: Test). Now I want to read the txt file and create a folder with the name Test. Every single line in list.txt should be a single folder.

I tried the following but it does not work:

def makefolder():
    with open('list.txt', 'r') as list:
        for line in list:
            os.mkdir()

I have a list.txt with simple names (for example: Test). Now I want to read the txt file and create a folder with the name Test. Every single line in list.txt should be a single folder.

I tried the following but it does not work:

def makefolder():
    with open('list.txt', 'r') as list:
        for line in list:
            os.mkdir()

Try the following

def makefolder():
    with open('list.txt', 'r') as list:
        for line in list:
            os.mkdir(line.strip())
makefolder()

you were missing to give the path as an argument in the os.mkdir(path) so in your code could be os.mkdir(line) just add strip() method will help you to remove extra spaces

import os

txtfile = open('test.txt', 'r')
lines = txtfile.readlines()
for line in lines:
        os.mkdir(line.rstrip("\n")) #inserting the name and taking out \n

I think you would need to remove the "\n" string to make the folders

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM