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
以及如何在不同的行而不是一行上打印这些数字?
答案 0 :(得分:1)
最简单的修复可能只是更改for
- 循环变量:
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
答案 1 :(得分:1)
打开文件。 f.readlines()
返回列表中文本文件中的每一行。
由于列表是从0开始编制索引的。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
答案 2 :(得分:0)
使用.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)
答案 3 :(得分:0)
使用以下代码: -
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
答案 4 :(得分:0)
文件是一个迭代器,这意味着您可以直接在文件上使用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
仍然是最后一行的编号,也就是总行数。