1

I have a python script in which I write on to a file the required data.Can I remove all that file writing part, and place in on to a module and somehow import it when required? I dont want to pass any values to the function written in module.I just want to replace the whole text with small line which can copy all the text from module.

Thank you

2 Answers 2

1

In addition to Lafada's answer:

If you don't want to pass any values to the function, then you can store all the necessary data in the module as well:

# mymodule.py

filename = 'c:\\temp\\fileout.txt'
data = """
       This is the
       multiline string\n
       which you want to write to the file
       """
...

def write_data_to_file():
    with open(filename, 'w') as fp:
        fp.write(data)

Assuming you have saved the above to mymodule.py, you call the function like so:

import mymodule
...

mymodule.write_data_to_file()

or, if that's the only function in the module that you need, and you want to use it lots, to save on typing:

from mymodule import write_data_to_file
...

write_data_to_file()

Note that mymodule.py must either be in the working directory of main script you are running or somewhere that is included in your PYTHONPATH environment variable.

See the python docs for more on modules.

Sign up to request clarification or add additional context in comments.

Comments

0

you can write a function which will write data to file.

def write_to_file(filename, data):
    with open(filename, 'w') as fp:
        fp.write(data)

You can write this function in a module and import in your module.

3 Comments

Its preferable to use with open(filename, 'w') as file: so that file is closed automatically when it exits the with.
Accepted your preferable use :)
Thats cool actually,I didnot know about "with open" thing.Solved lot of conflicts.Thank you :)

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.