Answers for "python save data to file"

9

python - save file

def save_to_file(content, filename):
    with open(filename, 'w') as file:
        file.write(content)

import file_operations
file_operations.save_to_file('my_content', 'data.txt')
Posted by: Guest on August-11-2020
5

how to save to file in python

with open('data.txt', 'w') as my_data_file:
   my_data_file.write(WhateverYourInputIs)
# After leaving the above block of code, the file is closed
# "w" overwrites the contents of the file
Posted by: Guest on October-07-2020
1

python store data in file

import pickle
file_name = 'data_stuff'
try:
    # this will create the file if it doesnt already exist
    history_data = open(file_name + ".dat", "x")
    history_data.close()
    history_data = []
    pickle.dump(history_data, open(file_name + ".dat", "wb"))
except:
    # if the file already exist it will load the history_data array 
    # you can add to it or modity it or just read it.
    history_data = pickle.load(open(file_name + ".dat", "rb"))

print(history_data) #this will print the history_data array that was stored in the file
foo = 5
history_data.append(foo)
print(history_data)
pickle.dump(history_data, open(file_name + ".dat", "wb")) # this saves the newly modified history_data to the file
Posted by: Guest on August-14-2021
1

how to write a python variable to a file

#use pickle

import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'w')
pickle.dump(dict, file)
file.close()

#and to read it again
file = open('dump.txt', 'r')
dict = pickle.load(file)
Posted by: Guest on May-04-2020

Python Answers by Framework

Browse Popular Code Answers by Language