簡體   English   中英

如何從輸出中刪除不需要的'\\ n'

[英]How to remove unwanted '\n' from output

file_4 = open('numbers.txt','r')
number_lines = 0
lines = file_4.readlines()[1:]
for file_4 in lines:
    number_lines += 1
print(lines)
print(number_lines)

output: ['2\n', '3\n', '4\n', '5']
         4

我的文本文件有5行

1
2
3
4
5

我希望輸出跳過第一行,並顯示其余部分。 如何擺脫/n ,又如何將這些數字分別打印在不同的行而不是一行上?

最簡單的解決方法可能是只更改for -loop變量:

file_4 = open('numbers.txt','r')
number_lines = 0
lines = file_4.readlines()[1:]
for line in lines:       # do not reuse previous variable here 
    number_lines += 1
    print(line.rstrip()) # strip the newline
print(number_lines)

似乎給出了您的預期輸出:

2
3
4
5
4

打開文件。 f.readlines()返回列表中文本文件中的每一行。

由於列表從0開始索引。list list[1:]將跳過第一個列表並給出其余的列表。

with open("stack.txt") as f:
    txt_list = f.readlines() #That's a list
    for item in txt_list[1:]: #skip the first one
        print(item)

輸出:

2

3

4

5

>>> 

\\n只是表示換行符的特殊字符。 從您的輸入中,您可以讀取多行,每行最后都有一個換行符 同時print在新行中打印每一個。 這就是上述輸出中兩個數字之間存在(兩個換行符)差距的原因。

您可以加入列表並像這樣打印。 因為每個已經有換行符 您正在做的是在代碼中打印整個列表。 你:

output: ['2\n', '3\n', '4\n', '5']

嘗試這個:

with open("stack.txt") as f:
    txt_list = f.readlines()
    out = ''.join(txt_list[1:])
print(out)

輸出:

2
3
4
5

使用.read().splitlines()

file_4 = open('numbers.txt','r')
lines = file_4.read().splitlines()[1:]      # .read().splitlines() will trim the newline chars
number_lines = len(lines)                   # We don't need a loop to count the number of lines
                                            #   We can use the `len` function.
print(lines)                                
print(number_lines)

但這會使file_4打開狀態,而您不必要地將整個文件讀入內存。

在這里,使用上下文管理器,循環遍歷文件的行,並使用.rstrip()修剪換行符:

with open('numbers.txt','r') as file_4:
    lines = [line.rstrip() for (i,line) in enumerate(file_4) if i > 0]

number_lines = len(lines)
print(lines)                                
print(number_lines)

使用以下代碼:

file_4 = open('numbers.txt','r')
number_lines = 0
lines = file_4.readlines()[1:]
# here we used map() to apply strip() function on each list item to remove \n
lines = map(str.strip, lines)
for file_4 in lines:
    number_lines += 1
# here we use join() with \n to print list item with new line.
print('\n'.join(lines))
print(number_lines)

輸出: -

2
3
4
5
4

文件是一個迭代器,這意味着您可以使用next並直接在文件上enumerate ,而不是立即將整個內容讀取到內存中。 使用strip刪除尾隨的換行符。 strip實際上刪除了所有前導和尾隨的空格; line.lstrip('\\n')會刪除特意尾隨的換行符。)

with open('numbers.txt', 'r') as file_4:
    next(file)  # skip the first line
    for count, line in enumerate(file_4, start=1):
        print(line.strip())
    print("Length:", count)

enumerate基本上號碼行(在這里,從1開始),以count為當前行號。 該循環退出后, count仍然是最后一行的數目,這也是行的總數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM