1

I want to copy the code in file A that has for example. string = "Awesome" and take it to file B that has length = len(string) print(length). Now this code is simple but the real one Im copying is longer so how can I successfully take all code to the other file.

Edit: I read what I was supposed to do wrong, So I have to make a function in this case mine is def copy(input, output): that takes the file name the user inputs and copies it to the output file. Both input and output are .txt files.

2
  • 3
    Be more specific. Do you want to replace or create the target file? What did you try? Commented Oct 12, 2015 at 19:44
  • 1
    I am confident that along with this homework assignment, you got some materials from which you are supposed to learn how to read and write from files. I suggest you check the assignment a third time, find out the associated reading, and go read it. If there's still something specific you don't understand, come back here on stackoverflow and I'm sure you'll find that your new questions have already been asked and answered. Commented Oct 12, 2015 at 20:34

2 Answers 2

1

Here is a simple example

def copy(file, target):
    with open(file) as fp, open(target, "w") as tp:
        tp.writelines(fp.readlines())

copy(input("File to copy"), input("Copy to"))

I haven't tested it but it should work fine. However I'd recommend using shutil.copy


If you want to do copy and execute/evaluate code in another file, unless it is a .py file, you could do

with open(filename) as fp:
    exec(fp.read())

len(´var_in_otherfile´)
Sign up to request clarification or add additional context in comments.

Comments

0

From what I can understand you want to "import" varaibales from script A to script B to do this you can do.

Heres an example.

File A

string = "Hello, World!"

File B

execfile('fileb.txt')
lenght = len(string)
print lenght

An alternative solution would be to make it a python module

File A = filea.py

string = "Hello, World!

File B = fileb.py

import filea as a
lenght = len(a.string)
print lenght

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.