【问题标题】:python reading lines in file and joining thempython读取文件中的行并加入它们
【发布时间】:2014-10-31 17:10:45
【问题描述】:

我有这个代码

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

我该如何解决这个问题?

【问题讨论】:

    标签: python join readline


    【解决方案1】:

    也许您应该使用 strip() 删除 newline
    示例

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

    readline() 一次读取一行,readlines() 将整个文件读取为行列表

    【讨论】:

      【解决方案2】:

      我从您的有限示例中猜测b 嵌入了换行符。那是因为readlines()。此处使用的 Python 习语是:ip.read().splitlines() 其中ip 是您的文件句柄之一。

      python docs查看更多分割线选项

      【讨论】:

        【解决方案3】:

        除了其他很好的答案之外,为了完整起见,我将使用string.translate 发布一个替代答案,这将涵盖任何\n 或换行符意外插入到字符串中间的情况,例如@ 987654323@,它将覆盖使用rstripstrip 的角落案例。

        服务器:x.x.x.x # U:882 # P:882 # Pre:900 # Tel:['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"))
        

        【讨论】:

          猜你喜欢
          • 2020-11-23
          • 1970-01-01
          • 2013-08-21
          • 2023-03-10
          • 2017-05-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-27
          相关资源
          最近更新 更多