python3 open file code example
Example 1: python write to file
with open(filename,"w") as f:
f.write('Hello World')
Example 2: python file reading
fin = open("NAME.txt", 'r')
body = fin.read().split("\n")
line = fin.readline().strip()
Example 3: python file open
file = open('C:\Users\yourname\files\file.txt','r')
text = file.read()
file = open('C:\Users\yourname\files\file.txt','w')
file.write('This is a typical string')
file.close()
Example 4: with open as file python
>>> with open('workfile') as f:
... read_data = f.read()
>>>
>>> f.closed
True
Example 5: how to write a python variable to a file
import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'w')
pickle.dump(dict, file)
file.close()
file = open('dump.txt', 'r')
dict = pickle.load(file)