with open('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
with open('filename', 'r') as f: # able to read data from file ( also is the default mode when opening a file in python)
with open('filename', 'x') as f: # Creates new file, if it already exists it will cause it to fail
with open('filename', 't') as f: # opens the file in text mode (also is defualt)
with open('filename', 'b') as f: # Use if your file will contain binary data
with open('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)
with open('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 file
print(fileText) # Prints the file text
#there are many modes you can open files in. r means read.
file = open('C:Usersyournamefilesfile.txt','r')
text = file.read()
#you can write a string to it, too!
file = open('C:Usersyournamefilesfile.txt','w')
file.write('This is a typical string')
#don't forget to close it afterwards!
file.close()
# 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+")
import os
my_computer = os.startfile("C:") # here c drive open this variable
print(my_computer)
f = open("test.txt", mode='r', encoding='utf-8')
with open("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()
import os
os.system('filename.extension')