open python code example

Example 1: python read file line by line

with open("file.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)

Example 2: 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 3: python with file.open

# Reference https://docs.python.org/3/library/functions.html#open

# Method 1
file = open("welcome.txt", "r") # mode can be r(read) w(write) and others 
data = file.read()
file.close()

# Method 2 - automatic close
with open("welcome.txt") as infile:
  data = file.read()

Example 4: with open python types

'r'	Open a file for reading. (default)
'w'	Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x'	Open a file for exclusive creation. If the file already exists, the operation fails.
'a'	Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't'	Open in text mode. (default)
'b'	Open in binary mode.
'+'	Open a file for updating (reading and writing)

Example 5: how to open a file in python

f = open("demofile.txt")

Example 6: *open(0) in python

stdout = open(1, "w")
stdout.write("Hello World") # Prints Hello World
stdout.close()