Opening Hours :7AM to 9PM
>>> f = open("test.txt") # open file in current directory >>> f = open("C:/Python38/README.txt") # specifying full pathWe can specify the mode while opening a file. In mode, we specify whether we want to read r, write w or append a to the file. We can also specify if we want to open the file in text mode or binary mode. The default is reading in text mode. In this mode, we get strings when reading from the file. On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like images or executable files.
Mode | Description |
---|---|
r | Opens a file for reading. (default) |
w | Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists. |
x | Opens a file for exclusive creation. If the file already exists, the operation fails. |
a | Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist. |
t | Opens in text mode. (default) |
b | Opens in binary mode. |
+ | Opens a file for updating (reading and writing) |
f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp",'r+b') # read and write in binary modeUnlike other languages, the character a does not imply the number 97 until it is encoded using ASCII (or other equivalent encodings).
f = open("test.txt", mode='r', encoding='utf-8')
f = open("test.txt", encoding = 'utf-8') # perform file operations f.write(“dfghjdfhg”) f.close()This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file. A safer way is to use a try...finally block.
try: f = open("test.txt", encoding = 'utf-8') # perform file operations finally: f.close()This way, we are guaranteeing that the file is properly closed even if an exception is raised that causes program flow to stop.
with open("test.txt", encoding = 'utf-8') as f: # perform file operations
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")This program will create a new file named test.txt in the current directory if it does not exist. If it does exist, it is overwritten.
>>> f = open("test.txt",'r',encoding = 'utf-8') >>> f.read() # read the first 4 data 'This' >>> f.read(4) # read the next 4 data ' is ' >>> f.read() # read in the rest till end of file 'my first file\nThis file\ncontains three lines\n' >>> f.read() # further reading returns empty string '' We can see that the read() method returns a newline as '\n'. Once the end of the file is reached, we get an empty string on further reading. We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our current position (in number of bytes). >>> f.tell() # get the current file position 56 >>> f.seek(0) # bring file cursor to initial position 0 >>> print(f.read()) # read the entire file This is my first file This file contains three lines We can read a file line-by-line using a for loop. This is both efficient and fast. >>> for line in f: ... print(line, end = '') ... This is my first file This file contains three linesIn this program, the lines in the file itself include a newline character \n. So, we use the end parameter of the print() function to avoid two newlines when printing. Alternatively, we can use the readline() method to read individual lines of a file. This method reads a file till the newline, including the newline character.
>>> f.readline() 'This is my first file\n' >>> f.readline() 'This file\n' >>> f.readline() 'contains three lines\n' >>> f.readline() '' Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading methods return empty values when the end of file (EOF) is reached. >>> f.readlines() ['This is my first file\n', 'This file\n', 'contains three lines\n']
def myfun(): f1=open("a.txt",mode="r", encoding = 'utf-8') f2=open("b.txt",mode="r", encoding = 'utf-8') x=int(f1.read()) y=int(f2.read()) z=x+y print(z) f1.close() f2.close() if __name__=="__main__": myfun()
def myfun(): x=int(input("Enter x value")) y=int(input("Enter y value")) z=x+y print(z) f = open("ouput.txt", mode="w", encoding = 'utf-8') f.write(str(z)) if __name__=="__main__": myfun()
class Demo: def __init__(self): f1=open("a.txt",mode="r", encoding = 'utf-8') f2=open("b.txt",mode="r", encoding = 'utf-8') self.x=int(f1.read()) self.y=int(f2.read()) f1.close() f2.close() def myfun(self): z=self.x+self.y print(z) f = open("ouput.txt", mode="w", encoding = 'utf-8') f.write(str(z)) f.close() if __name__=="__main__": d=Demo() d.myfun()
class Demo: def __init__(self): try: f1=open("a.txt",mode="r", encoding = 'utf-8') f2=open("b.txt",mode="r", encoding = 'utf-8') self.x=int(f1.read()) self.y=int(f2.read()) except NameError as n: print("Pls enter valid number") finally: f1.close() f2.close() def myfun(self): try: z=self.x+self.y print(z) f = open("ouput.txt", mode="w", encoding = 'utf-8') f.write(str(z)) except NameError as n: print("Pls enter valid number") finally: f.close() if __name__=="__main__": d=Demo() d.myfun()
class nerr(Exception): pass class Demo: def __init__(self): try: f1=open("a.txt",mode="r", encoding = 'utf-8') f2=open("b.txt",mode="r", encoding = 'utf-8') self.x=int(f1.read()) self.y=int(f2.read()) except NameError as n: print("Pls enter valid number") finally: f1.close() f2.close() def myfun(self): try: f = open("ouput.txt", mode="w", encoding = 'utf-8') if(self.x<0 or self.y<0): raise nerr else: z=self.x+self.y print(z) f.write(str(z)) except nerr: print("Pls enter positive number") except NameError as n: print("Pls enter valid number") finally: f.close() if __name__=="__main__": d=Demo() d.myfun()
import threading class nerr(Exception): pass class Demo(threading.Thread): def __init__(self): threading.Thread.__init__(self) try: f1=open("a.txt",mode="r", encoding = 'utf-8') f2=open("b.txt",mode="r", encoding = 'utf-8') self.x=int(f1.read()) self.y=int(f2.read()) except NameError as n: print("Pls enter valid number") finally: f1.close() f2.close() def run(self): try: f = open("ouput.txt", mode="w", encoding = 'utf-8') if(self.x<0 or self.y<0): raise nerr else: z=self.x+self.y print(z) f.write(str(z)) except nerr: print("Pls enter positive number") except NameError as n: print("Pls enter valid number") finally: f.close() if __name__=="__main__": d=Demo() d.start()