Reputation: 63
I am trying to randomly select a file in folder open it and write into it. I have:
import os, random
x = random.choice(os.listdir("F:\\1\\"))
y =open(x, 'w')
y.write('Hello World')
but nothing gets written. any ideas how to fix it?
Upvotes: 1
Views: 227
Reputation: 20414
This is very dangerous, as you opening a file
for writing
blanks
it of all its content, so you are effectively randomly
destroying one file
.
Anyway, if that is what you want, use a with
statement and remember that os.listdir
returns the file
names
in a directory, not paths
, so you need to use os.path.join
to join the 2
parts together:
import os, random
path = r"F:\1"
x = random.choice(os.listdir(path))
with open(os.path.join(path, x), 'w') as y:
y.write('Hello World')
Upvotes: 1
Reputation: 13090
The os.listdir
command lists all files in the given directory. It does not prepend the path (the directory name). You therefore have to do
import os, random
dirname = "F:\\1\\"
x = dirname + random.choice(os.listdir(dirname))
y = open(x, 'w')
y.write('Hello World')
Also, it is good practice to close a file once you are done writing to it. You can do this by y.close()
. This is done for you automatically if you use a with
statement like so:
import os, random
dirname = "F:\\1\\"
x = dirname + random.choice(os.listdir(dirname))
with open(x, 'w') as y:
y.write('Hello World')
Upvotes: 0
Reputation: 71451
The issue is that you are not closing the file:
import os, random
x = random.choice(os.listdir("F:\\1\\"))
y =open(x, 'w')
y.write('Hello World\n')
y.close()
Upvotes: 0