How can I open a file based on user input?
Profile icon
ANDREWVOSS

In the code:

inF = open(input("Enter Filename: "),'r') import inF inF

Is there any way I can import the filename that the user inputs?

You are viewing a single comment. View All
Profile icon
Coder100

You actually can!

__import__("file")

read this

Another way:

import os os.system("python3 [file].py")
Profile icon
ANDREWVOSS

@Coder100 Oh, Thanks!

Profile icon
Coder100
Profile icon
ANDREWVOSS

@Coder100 So if I structure it as

inF = open(input("Enter Filename: "),'r') __import__("inF") inF

How would I read the file?

Profile icon
Coder100

@ANDREWVOSS nooo
use it like import:

__import__(input("Enter Filename: "))
Profile icon
ANDREWVOSS

@Coder100 Sorry, let me rephrase that. How would I make it read the file that has been imported? eg:

import other.py other.py

where the other.py at the end outputs the file

Profile icon
ANDREWVOSS

@ANDREWVOSS nvm I found another way

program = input('Enter a program:') exec(program)
Profile icon
Coder100

@ANDREWVOSS um thats really bad

Profile icon
ANDREWVOSS

@Coder100 fair enough

Profile icon
ANDREWVOSS

@ANDREWVOSS still working on it

Profile icon
Coder100

Anyways, you should treat __import__ literally as import @ANDREWVOSS

Profile icon
ANDREWVOSS

Okay... @Coder100

Profile icon
Coder100

@ANDREWVOSS so like

__import__("other") other.func()

will work just fine (given you defined func)

Profile icon
Coder100

also

import other.py

is invalid, you mean:

import other

@ANDREWVOSS

Profile icon
ANDREWVOSS

@Coder100 Okay, I think I've got it. Thanks.

Profile icon
Coder100

great what did you do? @ANDREWVOSS

Profile icon
Coder100

yep that looks good @ANDREWVOSS

Profile icon
ANDREWVOSS

@Coder100 cool.

Profile icon
Coder100

mark as correct answer? @ANDREWVOSS

Profile icon
ANDREWVOSS

@Coder100
Screenshot 2020-09-21 at 10.02.37 AM
Is there a way to remove that error message?

Profile icon
ANDREWVOSS

@Coder100 there you go

Profile icon
Coder100

oh, type in file1 instead :) @ANDREWVOSS

Profile icon
Coder100

python is weird that way lol @ANDREWVOSS

Profile icon
Coder100

sorry for the late reply I was eating a sandwich @ANDREWVOSS

Profile icon
ANDREWVOSS

@Coder100 nah you're fine

Profile icon
ANDREWVOSS

@Coder100 thanks