Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3,从txt文件逐行读取,并将行拆分为两个变量_Python - Fatal编程技术网

Python3,从txt文件逐行读取,并将行拆分为两个变量

Python3,从txt文件逐行读取,并将行拆分为两个变量,python,Python,假设我有一个包含以下内容的文本文件: harry:arnold james:king jim:lin reece:inter 如何从文本文件中逐行读取并从:中拆分,并将firstname和lastname放入不同的值中,我以前的代码如下: with open(filepath) as fp: lines = fp.read().splitlines() with open(filepath, "w") as fp: for line in lines: 例

假设我有一个包含以下内容的文本文件:

harry:arnold
james:king
jim:lin
reece:inter
如何从文本文件中逐行读取并从:中拆分,并将firstname和lastname放入不同的值中,我以前的代码如下:

with open(filepath) as fp:
    lines = fp.read().splitlines()
with open(filepath, "w") as fp:
    for line in lines:

例如,如何在整个txt文件中添加firstname=harry,lastname=arnold,您需要在文件中循环并在冒号处打断

with open(filepath, 'r') as fp:
    result = []
    while 1:
        line = fp.readline()
        if len(line) == 0: #end of file break
            break
        result.append(line.split(':'))

print(result)
使用readlines读取文本,然后遍历文本

with open(filepath, 'r') as fp:
    lines = fp.readlines()
for x in lines:
    sp = x.split(":")
    firstname, lastname = sp[0], sp[1]
    print(firstname,lastname)

reece:inter.split':'会将字符串拆分为'reece'和'inter'。这是可行的,但也会在每个值的末尾打印一个空格,我该如何删除它?如果是这样的话,您需要剥离数据,请使用sp=x.split。split:love,谢谢,伙计