简体   繁体   English

在 Python 中逐行读取文件

[英]Reading a File Line by Line in Python

I am pretty new to Python.我对 Python 很陌生。 So I was trying out my first basic piece of code.所以我正在尝试我的第一个基本代码。 So i was trying to read a file and print it line by line in Python.所以我试图读取一个文件并在 Python 中逐行打印它。 Here is my code:这是我的代码:

class ReadFile(object):

    def main (self):

        readFile = ReadFile()
        readFile.printData()

    def printData(self):

        filename = "H:\\Desktop\\TheFile.txt"

        try:
            with open(filename, 'r') as f:
                value = f.readline()
                print(value)

            f.close()

        except Exception as ex:
            print(ex)

Now When I run it, I get no output.现在当我运行它时,我没有得到任何输出。 So I tried debugging it.所以我尝试调试它。 I see the control jumps from one method to another (main --> printData) and then exists.我看到控件从一种方法跳转到另一种方法(main --> printData)然后存在。 Its doesn't execute anything within the method.它不会在方法中执行任何操作。 Can you tell me what am I doing wrong here?你能告诉我我在这里做错了什么吗? I am new, so a little insight as to why the code is behaving this way would be nice as well.我是新来的,所以对代码为什么会以这种方式表现有一点了解也会很好。

If the idea here is to understand how to read a file line by line then all you need to do is:如果这里的想法是了解如何逐行读取文件,那么您需要做的就是:

with open(filename, 'r') as f:
  for line in f:
    print(line)

It's not typical to put this in a try-except block.将它放在 try-except 块中并不常见。

Coming back to your original code there are several mistakes there which I'm assuming stem from a lack of understanding of how classes are defined/work in python.回到您的原始代码,那里有几个错误,我假设这些错误源于缺乏对 Python 中类的定义/工作方式的理解。

The way you've written that code suggests you perhaps come from a Java background.您编写该代码的方式表明您可能具有 Java 背景。 I highly recommend doing one of the myriad free and really good online python courses offered on Coursera, or EdX.我强烈建议您学习 Coursera 或 EdX 上提供的无数免费且非常好的在线 Python 课程之一。


Anyways, here's how I would do it using a class:无论如何,这是我将如何使用类来做到这一点:

class ReadFile:
    def __init__(self, path):
        self.path = path

    def print_data(self):
        with open(self.path, 'r') as f:
            for line in f:
                print(line)

if __name__ == "__main__":
    reader = ReadFile("H:\\Desktop\\TheFile.txt")
    reader.print_data()

You don't really need a class for this and neither do you need a try block or a file.close when using a context manager (With open ....).你真的不需要一个类,在使用上下文管理器(打开......)时,你也不需要 try 块或 file.close 。

Please read up on how classes are used in python.请阅读如何在 python 中使用类。 A function will do for this一个函数将为此做

def read():

    filename = "C:\\Users\\file.txt"
       with open(filename, 'r') as f:
          for line in f:
             print(line)

There are a few problems here.这里有几个问题。

The first is that you are declaring a class but then not using it (except from within itself).第一个是你声明了一个类,但没有使用它(除了在它自身内部)。 You would need to create an instance of the class outside of the class (or call a class method on it) in order for it to be instantiated.您需要在类之外创建类的实例(或在其上调用类方法)才能实例化它。

class ReadFile:
    def print_data(self):
        ...

# Create a new object which is an instance of the class ReadFile
an_object = ReadFile()
# Call the print_data() method on an_object
an_object.print_data()

Now, you don't actually need to use classes to solve this problem, so you could ignore all this, and just use the code you have inside your printData method:现在,您实际上并不需要使用类来解决这个问题,因此您可以忽略所有这些,而只需使用您在 printData 方法中的代码:

filename = "H:\\Desktop\\TheFile.txt"

try:
    with open(filename, 'r') as f:
        value = f.readline()
        print(value)

# don't need to do this, as f is only valid within the
# scope of the 'with' block
#    f.close()

except Exception as ex:
    print(ex)

You will find this almost does what you want.您会发现这几乎可以满足您的需求。 You just need to modify it to print the entire file, not just the first line.您只需要修改它即可打印整个文件,而不仅仅是第一行。 Here, instead of just reading a single line with f.readline() we can iterate over the result of f.readlines() :在这里,我们可以迭代f.readlines()的结果,而不是仅仅使用f.readline()读取一行:

filename = "H:\\Desktop\\TheFile.txt"

try:
    with open(filename, 'r') as f:
        for value in f.readlines():  # read all lines
            print(value)

except Exception as ex:
    print(ex)

you don't usually put main method in a class.你通常不会把 main 方法放在一个类中。 Python is not like Java or C#. Python 不像 Java 或 C#。 all the code outside of class will execute when you load the file.加载文件时,类之外的所有代码都将执行。

you only create classes when you want to encapsulate some data with methods together in an object.只有当您想将一些数据与方法一起封装在一个对象中时,才创建类。 In your case it looks like you don't need a class at all, but if you want one you have to explicitly create and call it, for example:在您的情况下,您似乎根本不需要一个类,但是如果您想要一个类,则必须显式创建并调用它,例如:

class A:
    def __init__(self):
        print('constructor')

    def bang(self):
        print('bang')


# code outside of the class gets executed (like a 'main' method in Java/C#)
a = A()
a.bang()

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

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