Hello programmers, welcome post of interacting python with operating systems. Here, we will start discussion by interacting with operating system files first and deep into more later on. We will learn how to
- Open files
- Modify files
- Read files
- Read binary files
- Creating objects for file
- Iterating to file content
- All we will do by using python
To open a file in python we will use open method and pass file name and mode to open a file. We will give either
- Absolute path
- Relative path
Absolute path is full path of file irrespective of directory in which terminal is opened and relative path is dependent on directory. Mode is a single parameter that can be used to specify read, write, append mode etc. Source code is given below:
file = open('spider.txt')
# readline() method is used to read line of file one-by-one
print(file.readline())
# Displaying 2nd line
print(file.readline())
# read() method prints all lines of file
print(file.read())
# Preventing system to crash OR use with block to do same function
file.close()
'with' keyword in Python
with keyword in python is similar to open function with additional functionality of closing files automatically as humans made mistakes to close file. Sample code is given as:
# Automatically opens a file and closes it
# file object can be used anywhere in program
with open("spider.txt") as file:
print(file.readline())
Iterating through files in Python
We can easily iterate on each line of file using readline() function. Here, we will use with keyword and read each line by line. This is inner code of readlines() method that we can also use.with open("spider.txt") as file:
# Iterating on each line alternative to read() method
for line in file:
print(line.upper().strip()) # Removing newline characters alsofile = open("spider.txt")
# its not good way to store files data in variable as it uses more memory
lines = file.readlines()
file.close()
# Although we have closed a file but it is copied in object lines
lines.sort()print(lines)Writing Test in File
We can easily write text to file using 'w' mode. But this can overwrite existing data. In order to tackle over this situation we can use 'a' mode to append data in file without deleting previous data. Code is given below:
# Opening file in writing mode
with open("write.txt", "w") as file:
file.write("This is only strat of python that you are using")
# Appending data to already written file
with open("write.txt" , "a") as file:
file.write("\nThis is second line to check append works or not")
# Reading file in binary mode
with open("write.txt", 'r+b') as file:
print(file.readlines())