zigzs
zigzs

Reputation: 33

Opening a unique text file based on a random number

Opening a unique text file in Python based on a random number.

I'm using a random number generator to randomly open a text file, however my code will consist of a lot of if statements because I'm rather new and its the only way I know how. But there is a better way, because theres a better way in every programming language, I just need to know what it is. Heres my code:

n = random.randint(1, 3)
    print n
    if (n == 1):
         f = open('E:/1.txt', 'r')

I would obviously have to do this for every random number generated, so how can I...

f = open('E:/' & n & '.txt., 'r')

That obviously doesn't work, but hopefully you get the idea and can give me a hand.

Upvotes: 2

Views: 152

Answers (3)

Chris W.
Chris W.

Reputation: 39219

In python you use the str function to convert an integer to a string and the + operator to concatenate strings together.

n = random.randint(1, 3)
f = open('E:/' + str(n) + '.txt', 'r')

It would probably be better to use String Formatting though to get what you're looking for.

n = random.randint(1, 3)
f = open('E:/%s.txt' % n, 'r')

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113978

for i in range(3):
    n = random.randint(1,3)
    with open("E:\{0}.txt".format(n),"r") as f:
        #do something

Upvotes: 0

Wooble
Wooble

Reputation: 89897

Simply use string formatting:

n = random.randint(1, 3)
f = open('E:/%d.txt' % n, 'r')

Upvotes: 3

Related Questions