Python Forum
Import Python file with a name of a module in Stantard Library
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Import Python file with a name of a module in Stantard Library
#1
Hi,
I am doing a University Project and i need to import a file named time.py to the main projetc file that is main.py
The problem is that time is a module in Python Standart Library and when i run the program it is calling that module instead the time.py file.
I canĀ“t change the name of the file.
What shoud i do?
Thank you.
Reply
#2
Could you post your code so we can make suggestions?
Reply
#3
(Dec-06-2019, 06:39 PM)jefsummers Wrote: Could you post your code so we can make suggestions?

main.py File:

import time
x = 2
y = 3

print(time.soma(x,y))
time.py File:

def soma(x,y)

    result = x + y 
    return(result)
This is an example. The functios that i am going to put are others that i didnt make yet.
Reply
#4
You need a colon at the end of line 1 in time.py, but that does not solve the problem.
Scratching my head on this one, hopefully someone else has a solution.
Reply
#5
I have a solution. It is similar to code I wrote recently for another post, the idea being that in main.py you will copy the contents of time.py to another file, time1.py, and import that.
main.py
with open("time.py",'r') as file1:
    program = file1.readlines()

with open('time1.py','w') as file2:
    file2.writelines(program)

import time1

x = 2
y = 3
 
print(time1.soma(x,y))
time.py
def soma(x,y):
    return x+y
Reply
#6
Here is a solution I made:

class TimeModule():
	def __init__(self):
		self.globals = {}
	def __getattr__(self, key):
		return self.globals[key]

with open('time.py', 'r') as f:
	code = f.read()

time = TimeModule()
exec(code, time.globals)
Reply
#7
If your time.py is in the same folder as your main.py, then import time will import your file, not the one in the standard lib. The standard lib is at the bottom of the python_path, so it should never cause an issue if you want to override part of it.
Reply
#8
import time.py rather than import time

I think. Can you have a try?

Why can't you change the name of time.py? It is easiest way to solve the problem. Or, you can try jefsummers's solution, it works.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Frequency in first digit from csv file, NO IMPORT bryan0901 6 2,833 May-28-2020, 09:50 AM
Last Post: bryan0901
  How to create simple thread safe singletone that protect __init__ on import module umen 0 1,659 Apr-16-2020, 09:43 AM
Last Post: umen
  Math Module import Jack_Sparrow 3 6,429 Apr-30-2018, 01:41 PM
Last Post: snippsat
  Import a Data from a text file maxcom 1 2,420 Apr-01-2018, 07:30 PM
Last Post: Larz60+
  Import random from a txt file Liquid_Ocelot 4 7,494 May-05-2017, 10:14 PM
Last Post: Liquid_Ocelot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020