-1

I wrote a python code and saved it

(let's say I saved it in (C:\Users\MyCode\Code1.py) )

and I'm writing a new python code, and I would like to copy everything from Code1.

I just opened Code1.py and copied and pasted it, but is there a smarter way to do it?

(thanks for the answers so far, but let's assume that the code that I'm trying to copy and the code that I'm writing are not in the same directory)

user98235
  • 830
  • 1
  • 13
  • 31
  • It is unclear to me exactly what you are trying to accomplish... Do you want to copy source code from one file to another? Or just use some of the code you written in one script in a other. I.e. like importing a module. – juanpa.arrivillaga Jan 13 '18 at 23:43

2 Answers2

1

You can do something like this:

Code1.py

def hello():
    print("Hello")

New file

import Code1

Code1.hello() # "Hello"

This way you don't have to copy and paste all the code.


If the file you are trying to import is not in the same directory...

Here is a possible answer to your question taken from here.

By default, you can't. When importing a file, Python only searches the current directory, the directory that the entry-point script is running from, and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases). However, you can add to the Python path at runtime:

# some_file.py
import sys
sys.path.insert(0, '/path/to/application/app/folder')

import file
23k
  • 1,596
  • 3
  • 23
  • 52
0

If both files are on the same directory you could try:

from Code1 import *

You could also include your file to the python path. That is, if you have something like this:

dir\
    Code1.py
    other_dir\
        code.py

You could do in code.py:

import sys

sys.path.append('..')

from Code1 import *

This works (by inserting its parent directory to the path) but I would avoid doing this on production code as seems very wrong. Instead you may want to check out python packaging (https://packaging.python.org/).

bla
  • 1,840
  • 1
  • 13
  • 17