withopen('filename','a')as f:# able to append data to file
f.write(var1)# Were var1 is some variable you have set previously
f.write('data')
f.close()# You can add this but it is not mandatory withopen('filename','r')as f:# able to read data from file ( also is the default mode when opening a file in python)withopen('filename','x')as f:# Creates new file, if it already exists it will cause it to failwithopen('filename','t')as f:# opens the file in text mode (also is defualt)withopen('filename','b')as f:# Use if your file will contain binary datawithopen('filename','w')as f:# Open file with ability to write, will also create the file if it does not exist (if it exists will cause it to fail)withopen('filename','+')as f:# Opens file with reading and writing# You can combine these as you like with the + for reading and writing
fileName ="file_name.txt"#Here you need to write the file name as a string
openLike =""#Here you need to write how do you want to open the file:#"w": Write, "r": Read
openedFile =open("file_name.txt", openLike)#Here you open the file
fileText = openedFile.read()#This read all the file
openedFile.close()#Close the fileprint(fileText)# Prints the file text
x =open("filename.txt","r")print(x.read())#if file is a txt file this will print the text#Make sure the file is in the same directory as were your python file is opened in.#you can also make a var out of your text by doing:
var = x.read()#or
var =open("filename.txt","r").read()
# Open function to open the file "MyFile1.txt" # (same directory) in append mode and
file1 =open("MyFile.txt","a")# store its reference in the variable file1 # and "MyFile2.txt" in D:Text in file2
file2 =open(r"D:TextMyFile2.txt","w+")
withopen("cars.txt")as cars:#open cars.txt file declaration cars variable then assign cars.txt data
blue_cars = cars.read()#read cars.txt data and assign to blue_cars#advantage using this, implicitly applied cars.close() method------Similar to ----
cars =open("cars.txt")
blue_cars = cars.read()
cars.close()