Python - is it always recommended to open a file with mode "b"?

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 
+5
source share
1 answer

In Python 2.7 tutorial: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

On Windows, the 'b' added to mode opens the file in binary mode, so there are also modes such as "rb", "wb" and "r + b". Python on Windows makes a distinction between text and binary; end of line characters in text files automatically change when data is read or written. This off-screen file data modification is great for ASCII text files, but itll corrupt binary data like this in JPEG or EXE files. Be very careful when using binary mode when reading and writing such files. On Unix, it doesn't hurt to add β€œb” to mode, so you can use its platform-independently for all binaries.

My installment from this uses "rb", it seems to be the best, and it looks like you are facing the problem they are warning about - opening the binary with "r" on Windows.

+4
source

Source: https://habr.com/ru/post/1213912/


All Articles