Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取文件对象上的行和循环_Python - Fatal编程技术网

Python 读取文件对象上的行和循环

Python 读取文件对象上的行和循环,python,Python,我试图从一个文件中读取行并在一个循环中打印它们,这是可行的,但我在每个打印语句之后都会得到新行 这是我的班级 class FileReader: """Reads a file from args""" def __init__(self, args): input = '' with open(args, 'r') as rFile: for line in rFile: print(lin

我试图从一个文件中读取行并在一个循环中打印它们,这是可行的,但我在每个打印语句之后都会得到新行

这是我的班级

class FileReader:
    """Reads a file from args"""
    def __init__(self, args):
        input = ''
        with open(args, 'r') as rFile:
            for line in rFile:
                print(line)
我的输入文件是这样的。(“$”是新行):

我的输出变成:

12 3

2

9

5

3 4

我得到这些空格的原因是什么?

每个
print
命令都会在末尾自动添加一个换行符。由于您的文件在每行末尾都有一个换行符(根据定义),因此您的程序将连续输出两个换行符

例如,尝试以下方法:

for i in xrange(10):
    print(str(i) + '\n')
您将获得与代码相同的“问题”


如果要修复该行为,请将
print(line)
替换为
print(line.rstrip())
,这将从每行末尾删除所有空白字符。如果您的行以制表符或空格结尾,这可能会有问题;在这种情况下,请使用打印行.rstrip('\n'),这只会删除换行符。

当您循环文件时,生成的行包括行末尾的换行符。使用
print()

您可以使用
.strip()
删除行首和行尾的空白,包括换行符

如果只想删除末尾的换行符,请使用
line[:-1]
line.rstrip('\n')
将其删除

最后但并非最不重要的一点是,您还可以告诉
print()
不要添加换行符:

print(line, end='')

如果您不想要新线路,请使用rstrip。例如:

print(line.rstrip())

请注意,有些文件使用换行+回车=两个字符。最好使用
line.rstrip()
。OP可能使用的是Python 3,因为
print()
被用作函数。@moooeeep:good point。我相应地编辑了答案,谢谢。@moooeeep:如果文件不是以二进制模式打开的,换行符将被合理地处理。
print(line.rstrip())