Skip to content Skip to sidebar Skip to footer

Python Reading Whitespace-separated File Lines As Separate Lines

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 separates ou

Solution 1:

This isn't a Python problem. This is an OS issue. I presume you're running Linux (you didn't say).

Running this:

mkdir Line with multiple words

... will create four directories, not one.

UPDATE: @bgporter explains this too.

The much better solution is not to use os.system (basically, ever) but to use os.mkdir instead:

import os
f = open("out.txt", "r")
os.chdir("base location")
for line in f:
    s = line.strip()
    iflen(s)>0:
        # ignore blank or whitespace-only linesos.mkdir(s)

Solution 2:

If you run:

mkdir hello world

in Linux, you will create two directories, one named "hello", and one named "world".

You need to run

mkdir "hello world"

in order to create a directory name that has a space in it.

Solution 3:

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())

Solution 4:

Without sample input it is hard to be sure, but it looks like you need to quote the directory creation.

for line in f:
    os.system("mkdir '%s'" % line.strip())

On Windows, the single quotes will cause undesirable effects, so using double quotes is probably necessary.

for line in f:
    os.system('mkdir "%s"' % line.strip())

Solution 5:

Replace this line:

os.system("mkdir " + line.strip())

with

os.system("mkdir '{0}'".format(line.strip()))

By quoting the argument to mkdir you tell it to create a single directory that has a name containing whitespace. If the quotes are omitted, mkdir creates multiple directories instead.

Post a Comment for "Python Reading Whitespace-separated File Lines As Separate Lines"