简体   繁体   English

使用 rstrip("\\n") 从 readlines 中删除 \\n

[英]Removing \n from readlines with rstrip("\n")

im reading 2 files per lines that contains strings and grouping per other one here in my code im grooping 1 line from proxyfile with 3 lines from websitefiles major problem when i try to print the lines from 2nd file i cant remove the \\n我在我的代码中每行读取 2 个包含字符串的文件,并在我的代码中对每个文件进行分组,我从代理文件中提取 1 行,从网站文件中提取 3 行当我尝试打印第二个文件中的行时,主要问题是我无法删除 \\n

i have tried to use rstrip("\\n") but i got this exception我曾尝试使用 rstrip("\\n") 但我遇到了这个异常

AttributeError: 'tuple' object has no attribute 'rstrip'

this is my code :这是我的代码:

proxy = open("proxy.txt",'r')
readproxy = proxy.readlines()

sites = open("websites.txt",'r')
readsites = sites.readlines()

for i,j in zip(readproxy, zip(*(iter(readsites),) * 3)):

    try:
        i = i.rstrip("\n")
        #j = j.rstrip("\n")
        print(i,j)
    except ValueError:
        print 'whatever'

i removed the \\n from "i" successfully , but coudent remove it from "j"我成功地从“i”中删除了\\n,但是从“j”中删除了它

this screenshot can explain all i think这个截图可以解释我认为的一切屏幕1

A tuple doesn't have a method that magically propagates to all string elements. tuple没有神奇地传播到所有字符串元素的方法。

To do that you have to apply rstrip for all items in a list comprehension to create a list .为此,您必须对列表理解中的所有项目应用rstrip以创建list

j = [x.rstrip("\n") for x in j]

that rebuilds a list with items stripped.重建一个删除项目的list Convert to tuple if really needed:如果确实需要,转换为tuple

j = tuple(x.rstrip("\n") for x in j)

note that you could avoid this post processing by doing:请注意,您可以通过执行以下操作来避免此后处理:

readsites = sites.read().splitlines()

instead of sites.readlines() since splitlines splits into lines while removing the termination character if no argument is specified.而不是sites.readlines()因为如果没有指定参数, splitlines在删除终止字符时拆分成行。 The only drawback is in the case when the file is huge.唯一的缺点是在文件很大的情况下。 In that case, you could encounter a memory issue (memory needed by read + split is doubled).在这种情况下,您可能会遇到内存问题(读取 + 拆分所需的内存加倍)。 In which case, you could do:在这种情况下,你可以这样做:

with open("websites.txt",'r') as sites:
    readsites = [line.rstrip("\n") for line in sites]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM