There are several ways to read a file in Python, here are a few examples:
- Using the open() function:
with open('codeHub.txt', 'r') as file: content = file.read() print(content)
In this example, the open() function is used to open the file ‘example.txt’ in read mode (‘r’). The ‘with open’ statement is used to ensure that the file is properly closed after reading.
The file.read() method is used to read the contents of the file. The contents are then stored in a variable called ‘content’ and printed to the console using the print() function.
- Using the read() method:
file = open('codeHub.txt', 'r') content = file.read() print(content) file.close()
This example is similar to the previous one, but it uses the file.read() method to read the contents of the file and assigns the results to a variable called ‘content’. The file.close() method is used to close the file after it has been read.
- Using the readlines() method:
file = open('codeHub.txt', 'r') content = file.readlines() for line in content: print(line) file.close()
This example uses the file.readlines() method to read the contents of the file and assigns the results to a variable called ‘content’. The for loop is used to iterate over the lines in the ‘content’ variable and print each line.
- Using ‘with open’ and for loop
with open("codeHub.txt", "r") as file: for line in file: print(line)
This example uses ‘with open’ to open the file and for loop to iterate through the lines in the file, printing each line.
In all the examples, ‘codeHub.txt’ is the file you want to read, and 'r'
is the mode in which the file is opened (r stands for read mode).
The file can also be opened in different modes such as ‘r'(read), ‘w'(write), ‘a'(append), ‘b'(binary), and so on. When you are done reading the file, it is a good practice to close the file by calling the file.close() method or using the ‘with open’ statement.
So let’s start coding within the next blog. If you’ve got any questions regarding this blog, please let me know in the comments.