python open write and read code example

Example 1: python read file

with open("file.txt", "r") as txt_file:
  return txt_file.readlines()

Example 2: python open and reacd file

with open('yourfile.txt','r') as f:
    lines = f.readlines()
    f.close()

Example 3: 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)

Example 4: read and write to file python

file = open(“testfile.txt”, “r+)

Example 5: python create file

f= open("guru99.txt","w+")

Example 6: read and write file in python

#Write a Python program to create a file of numbers by taking input from the user and then display the content of the file. You can take input of non-zero numbers, with an appropriate prompt, from the user until the user enters a zero to create the file assuming that the numbers are non-zero.  
    f = open ('NumFile.txt','w')
    while True :
        no = int(input("enter a number (0 for exit)"))
        if no == 0 :
            print("you entered zero(0) ....... \n now you are exit  !!!!!!!!!!!")
            break
        else :
            f.write(str(no)+"\n")
    f.close() 
    f1 = open ('NumFile.txt','r')
    print("\ncontent of file :: \n",f1.read())
    f1.close()