
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to share common data among multiple Python files?
You're not going to be able to share common data between multiple Python files without storing the information somewhere external to the two instances of the interpreter. Either you have to use a networking/socket setup - or you have to use temporary files. The easiest way is to use a file to share the data. You can use the pickle module to store objects to file from one script and use another script to open that file and deserialize the file as an object. For example,
In the file you want to write the object from −
producer.py: import pickle shared = {"Foo":"Bar", "Parrot":"Dead"} fp = open("shared.pkl","w") pickle.dump(shared, fp)
In the file where you want to consume this object −
consumer.py: import pickle fp = open("shared.pkl") shared = pickle.load(fp) print shared["Foo"]
- Related Articles
- How to share private members among common instances in JavaScript?
- Python - Write multiple files data to master file
- How to rename multiple files recursively using Python?
- Rename multiple files using Python
- How to rename multiple files in a directory in Python?
- How to delete multiple files in a directory in Python?
- Common words among tuple strings in Python
- How to merge multiple files into a new file using Python?
- How to spilt a binary file into multiple files using Python?
- How to combine multiple R data frames that contains one common column?
- How we can split Python class into multiple files?
- How to combine multiple R data frames stored in multiple lists based on a common column?
- How to Convert Multiple XLS Files to XLSX Files in Excel?
- How to plot data from multiple two-column text files with legends in Matplotlib?
- How to read multiple text files from a folder in Python?(Tkinter)

Advertisements