Python reading whitespace-separated file lines as separate lines

后端 未结 6 776
野性不改
野性不改 2021-01-25 14:18

This is on Windows Server 2008 R2. I have a file of inputs, one input per line. Some of the inputs have spaces in them. I\'m trying to use the below simple code, but it separate

6条回答
  •  礼貌的吻别
    2021-01-25 14:59

    The other answers here are all right -- the problem has to do with how Unix commands work -- if you want to use mkdir to create a directory with a name containing spaces, you have to either escape the spaces or put quotes around the name so that your Unix environment knows there is only one argument, and it has spaces in it; otherwise, it will make one directory per argument/word.

    I just want to add 2 things:

    1. Whenever you open() a file, you need to make sure you close() it. The easiest way to do this is to use a context manager, like with open(file) as f:.

    2. os actually has a mkdir function that takes a string as an argument. You could just pass each line to os.mkdir as-is.

    So, you could revise your code like this:

    import os
    
    with open("out.txt", "r") as f:
        os.chdir("base location")
    
        for line in f:
            os.mkdir(line.strip())
    

提交回复
热议问题