在 Python 中逐行读取文件 [英] Reading a File Line by Line in Python
问题描述
我对 Python 还很陌生.所以我正在尝试我的第一个基本代码.所以我试图读取一个文件并在 Python 中逐行打印它.这是我的代码:
I am pretty new to 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. 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)
现在当我运行它时,我没有得到任何输出.所以我尝试调试它.我看到控件从一种方法跳转到另一种方法(main --> printData)然后存在.它不会在方法中执行任何操作.你能告诉我我在这里做错了什么吗?我是新来的,所以对代码的行为方式有一点了解也会很好.
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. 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)
将它放在 try-except 块中并不常见.
It's not typical to put this in a try-except block.
回到您的原始代码,我假设其中有几个错误是由于缺乏对 Python 中类的定义/工作方式的理解.
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.
您编写该代码的方式表明您可能具有 Java 背景.我强烈建议您学习 Coursera 或 EdX 上提供的无数免费且非常好的在线 Python 课程之一.
The way you've written that code suggests you perhaps come from a Java background. I highly recommend doing one of the myriad free and really good online python courses offered on Coursera, or EdX.
无论如何,这是我使用类的方法:
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()
这篇关于在 Python 中逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!