文章内容
2020/12/17 18:38:48,作 者: 黄兵
python 使用readlines()读文件的时候\r\n
下面是使用Python读取一个txt文件的示例:
@staticmethod
def read_config():
black_list_path = os.path.join(os.getcwd(), f'config\\black_list.txt')
if os.path.exists(black_list_path):
with open(black_list_path, 'r', encoding='utf-8', newline='') as txt_file:
black_list = txt_file.readlines()
return black_list
但是这样读取会产生\r\n
的多余字符,截图如下:
这里会存在一些问题,所以需要把后面的\r\n
去掉,修改代码如下:
@staticmethod
def read_config():
black_list_path = os.path.join(os.getcwd(), f'config\\black_list.txt')
if os.path.exists(black_list_path):
with open(black_list_path, 'r', encoding='utf-8', newline='') as txt_file:
black_list = [line.rstrip() for line in txt_file]
return black_list
这里循环每一行,之后去掉后面的\r\n
。
参考资料:
1、Getting rid of \n when using .readlines() [duplicate]
黄兵个人博客原创。
评论列表