i am trying to make a python program that randomly selects a text file to open and outputs the contents of the randomly selected text file
when i try running the code, i get this error
Traceback (most recent call last): File "//fileserva/home$/K59046/Documents/project/project.py", line 8, in o = open(text, "r") TypeError: expected str, bytes or os.PathLike object, not tuple
this is the code that i have written
import os
import random
os.chdir('N:\Documents\project\doodoo')
a = os.getcwd()
print("current dir is",a)
file = random.randint(1, 4)
text = (file,".txt")
o = open(text, "r")
print (o.read())
can somebody tell me what i am doing wrong?
CodePudding user response:
As your error message says, your text
variable is a tuple, not a string. You can use f-strings or string concatenation to solve this:
# string concatenation
text = str(file) ".txt"
# f-strings
text = f"{file}.txt"
CodePudding user response:
Your variable text
is not what you expect. You currently create a tuple that could look like this: (2, ".txt")
. If you want a string like "2.txt"
, you need to concatenate the two parts:
text = str(file) ".txt"