0
Q:

python open and reacd file

with open('yourfile.txt','r') as f:
    lines = f.readlines()
    f.close()
1
#reading a txt file using a context manager
with open("my_file.txt","r") as text:
  print(text.readlines())			#prints a list of lines in the txt file
  print(text.readline())			#prints the first line of the txt file
  print(text.read(4))				#prints the first four characters of the txt file
3
# "with" closes file for you after use, even if error encountered
# r - read, w - write, rb - read binary, wb - write binary

with open('dog_breeds.txt', 'r') as reader:
     # Read and print the entire file line by line
     for line in reader:
         print(line, end='')
8
file = open(“testfile.txt”, “r+”) 
5
with open('pagehead.section.htm','r') as f:
    output = f.read()
2
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
7

  f = open("demofile.txt", "r")
print(f.read()) 
-1

New to Communities?

Join the community