我处理的小需求是,将文件中每一行取出来,同时去掉换行符
file_path = 'a.txt'
arr = open(file_path).readlines()
# ['a1\n', 'a2\n']
print(arr[:2])
arr1 = [x.strip() for x in arr]
print(arr1[:2])
# ['a1', 'a2']
简单点:
arr = [x.strip() for x in open(file_path).readlines()]
print(arr[:2])
参考:16个非常有用的Python单行代码!
https://www.sohu.com/a/707569420_121124376