python with open file 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: python read file
with open("file.txt", "r") as txt_file:
return txt_file.readlines()
Example 3: python write to file
with open(filename,"w") as f:
f.write('Hello World')
Example 4: python open file
with open('filename', 'a') as f:
f.write(var1)
f.write('data')
f.close()
with open('filename', 'r') as f:
with open('filename', 'x') as f:
with open('filename', 't') as f:
with open('filename', 'b') as f:
with open('filename', 'w') as f:
with open('filename', '+') as f:
Example 5: python with file.open
file = open("welcome.txt", "r")
data = file.read()
file.close()
with open("welcome.txt") as infile:
data = file.read()
Example 6: python write to file
path = "guide/README.txt"
with open(path, "w") as fil:
fil.write("This is the README. It is reccomended that you read it.")
fil.close()
'''
List of methods:
w* - replace everything with needed text
r^ - read the file
a* - adds to file
x - creates file
* Creates file if the file at that path does not exist
^ Throws error if file does not exist
'''