Python读取文件中的行并连接它们

-2 投票
3 回答
623 浏览
提问于 2025-04-30 21:58

我有这段代码

with open ('ip.txt') as ip :
    ips = ip.readlines()
with open ('user.txt') as user :
    usrs = user.readlines()
with open ('pass.txt') as passwd :
    passwds = passwd.readlines()
with open ('prefix.txt') as pfx :
    pfxes = pfx.readlines()
with open ('time.txt') as timer :
    timeout = timer.readline()
with open ('phone.txt') as num :
    number = num.readline()

它会打开所有这些文件,并把它们合并成这个样子

result = ('Server:{0} # U:{1} # P:{2} # Pre:{3} # Tel:{4}\n{5}\n'.format(b,c,d,a,number,ctime))
print (result)
cmd = ("{0}{1}@{2}".format(a,number,b))
print (cmd)

我本以为它会打印成这样

Server:x.x.x.x # U:882 # P:882 # Pre:900 # Tel:456123456789
900456123456789@x.x.x.x

但实际输出却是这样

Server:x.x.x.x
 # U:882 # P:882 # Pre:900
 # Tel:456123456789
900
456123456789@187.191.45.228

新的输出是:

Server:x.x.x.x # U:882 # P:882 # Pre:900 # Tel:['456123456789']
900['456123456789']@x.x.x.x

我该怎么解决这个问题呢?

暂无标签

3 个回答

0

除了其他很棒的回答,为了完整起见,我在这里提供一个使用 string.translate 的替代方案。这种方法可以处理字符串中意外插入的 \n 或换行符,比如 '123\n456\n78',这样可以避免使用 rstripstrip 时出现的边缘情况。

服务器:x.x.x.x # 用户:882 # 密码:882 # 前置:900 # 电话:['456123456789']

900['456123456789']@x.x.x.x

你看到这个是因为你在打印一个列表。要解决这个问题,你需要把列表中的字符串 number 连接起来。

总的来说,解决方案大概是这样的:

import string

# prepare for string translation to get rid of new lines
tbl = string.maketrans("","")

result = ('Server:{0} # U:{1} # P:{2} # Pre:{3} # Tel:{4}\n{5}\n'.format(b,c,d,a,''.join(number),ctime))
# this will translate all new lines to ""
print (result.translate(tbl, "\n"))
cmd = ("{0}{1}@{2}".format(a,''.join(number),b))
print (cmd.translate(tbl, "\n"))
0

我猜根据你给的简单例子,b 里面可能有换行符。这是因为你用了 readlines() 这个方法。在这里,推荐你使用的 Python 写法是:ip.read().splitlines(),其中 ip 是你打开的文件句柄之一。

想了解更多关于 splitlines 的用法,可以查看 Python 文档

1

也许你应该用 strip() 来去掉 newline(换行符)。


示例:
with open ('ip.txt') as ip :
    ips = ip.readline().strip()

readline() 是一次读取一行,而 readlines() 是把整个文件作为一系列行读取。

撰写回答