read and write file python code example
Example 1: python make txt file
file = open("text.txt", "w")
file.write("Your text goes here")
file.close()
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
Example 2: python write to file
file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close()
Example 3: python write to file
with open(filename,"w") as f:
f.write('Hello World')
Example 4: open file python
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
Example 5: python write to file
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
Example 6: python write to file
# using 'with' block
with open("xyz.txt", "w") as file: # xyz.txt is filename, w means write format
file.write("xyz") # write text xyz in the file
# maunal opening and closing
f= open("xyz.txt", "w")
f.write("hello")
f.close()
# Hope you had a nice little IO lesson