Ask coding questions

← Back to all posts
How can I open a file based on user input?
ANDREWVOSS (5)

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?

Answered by Coder100 (8320) [earned 5 cycles]
View Answer
Commentshotnewtop
Coder100 (8320)

You actually can!

__import__("file")

read this

Another way:

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

@Coder100 So if I structure it as

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

How would I read the file?

Coder100 (8320)

@ANDREWVOSS nooo
use it like import:

__import__(input("Enter Filename: "))
ANDREWVOSS (5)

@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

ANDREWVOSS (5)

@ANDREWVOSS nvm I found another way

program = input('Enter a program:')
exec(program)
Coder100 (8320)

Anyways, you should treat __import__ literally as import @ANDREWVOSS

Coder100 (8320)

@ANDREWVOSS so like

__import__("other")
other.func()

will work just fine (given you defined func)

Coder100 (8320)

also

import other.py

is invalid, you mean:

import other

@ANDREWVOSS

ANDREWVOSS (5)

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

Coder100 (8320)

mark as correct answer? @ANDREWVOSS

ANDREWVOSS (5)

@Coder100

Is there a way to remove that error message?

Coder100 (8320)

oh, type in file1 instead :) @ANDREWVOSS

Coder100 (8320)

python is weird that way lol @ANDREWVOSS

Coder100 (8320)

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

ZDev1 (615)
inF = input('Filename:\n> ')

try:
    with open(f'{inF}', 'r') as file:
        pass
except:
    print('This file is not defined')
InvisibleOne (300)

As far as I know, you can't. I'm interested to know why you want to do this? What are you trying to make?

ANDREWVOSS (5)

@InvisibleOne I was mostly just wondering, but I also wanted to make a program that could be used to seamlessly launch other programs from it.

ANDREWVOSS (5)

@InvisibleOne I think I'll post it in Share