环境:centos7.6
python版本:python3.7
需求:获取/etc/passwd这个文件的第一列和最后一列,并存入各自的list中。
import codecs
filePath = '/etc/passwd'
firstCol = []
lastCol = []
def cutStr():
with codecs.open(filePath, 'r', encoding='utf-8') as file:
for line in file.readlines():
str1 = line.split(":")
firstCol.append(str1[0:1])
lastCol.append(str1[-1])
if __name__ == '__main__':
cutStr()
print('第一列:')
print(firstCol + '\n')
print('最后一列:')
print(lastCol + '\n')