So I have this simple python function:
def ReadFile(FilePath): with open(FilePath, 'r') as f: FileContent = f.readlines() return FileContent
This function is common and is used to open all files. However, when the file is open, it is a binary file, this function does not work properly. Changing open () calls:
with open(FilePath, 'rb') as f:
solve the problem for binary files (and seems to be saved in text files)
Question:
- Is it safe and recommended to always use
rb mode to read a file? - If not, in what cases is it harmful?
- If not, how do you know which mode to use if you donβt know what type of file you are working with?
Update
FilePath = r'f1.txt' def ReadFileT(FilePath): with open(FilePath, 'r') as f: FileContent = f.readlines() return FileContent def ReadFileB(FilePath): with open(FilePath, 'rb') as f: FileContent = f.readlines() return FileContent with open("Read_r_Write_w", 'w') as f: f.writelines(ReadFileT(FilePath)) with open("Read_r_Write_wb", 'wb') as f: f.writelines(ReadFileT(FilePath)) with open("Read_b_Write_w", 'w') as f: f.writelines(ReadFileB(FilePath)) with open("Read_b_Write_wb", 'wb') as f: f.writelines(ReadFileB(FilePath))
where f1.txt :
line1 line3
Files Read_b_Write_wb , Read_r_Write_wb and Read_r_Write_w eqauls for source f1.txt .
Read_b_Write_w file:
line1 line3
source share