Python,检查数据文件中的某些行
我从来没有上过使用 python 的课程,只上过 c、c++、c#、java 等。 这应该很容易,但我感觉我错过了 python 反应的一些巨大的东西。 我所做的就是读取文件,检查仅包含数字的行,计算类似的行数并显示它。
所以我打开、读取、条带化、检查 isdigit() 并递增。怎么了?
# variables
sum = 0
switch = "run"
print( "Reading data.txt and counting..." )
# open the file
file = open( 'data.txt', 'r' )
# run through file, stripping lines and checking for numerics, incrementing sum when neeeded
while ( switch == "run" ):
line = file.readline()
line = line.strip()
if ( line.isdigit() ):
sum += 1
if ( line == "" ):
print( "End of file\ndata.txt contains %s lines of digits" %(sum) )
switch = "stop"
I've never taken a class that used python, just c, c++, c#, java, etc..
This should be easy but I'm feeling like I'm missing something huge that python reacts to.
All I'm doing is reading in a file, checking for lines that are only digits, counting how many lines like that and displaying it.
So I'm opening, reading, striping, checking isdigit(), and incrementing. What's wrong?
# variables
sum = 0
switch = "run"
print( "Reading data.txt and counting..." )
# open the file
file = open( 'data.txt', 'r' )
# run through file, stripping lines and checking for numerics, incrementing sum when neeeded
while ( switch == "run" ):
line = file.readline()
line = line.strip()
if ( line.isdigit() ):
sum += 1
if ( line == "" ):
print( "End of file\ndata.txt contains %s lines of digits" %(sum) )
switch = "stop"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 Python 中判断是否已到达文件末尾的正确方法是而不是查看它是否返回空行。
相反,迭代文件中的所有行,当到达文件末尾时循环将结束。
因为文件可以迭代,所以您可以使用生成器表达式来简化它:
我还建议不要使用保留的 Python 关键字(例如
sum
)作为变量名,而且使用字符串比较进行流程也是非常低效的就像你正在做的逻辑。The correct way in Python to tell if you've reached the end of a file is not to see if it returns an empty line.
Instead, iterate over all the lines in the file, and the loop will end when the end of the file is reached.
Because files can be iterated over, you can simplify this using a generator expression:
I would also recommend against using reserved Python keywords such as
sum
as variable names, and it's also terribly inefficient to use string comparisons for flow logic like you're doing.我刚刚尝试运行你的代码:
它在这里工作正常。你的data.txt里有什么?
I just tried running your code:
It works fine here. What's in your data.txt?
正如几个人所说,您的代码似乎运行完美。也许您的“data.txt”文件位于与当前工作目录不同的目录中(不一定是脚本所在的目录)?
然而,这里有一种更“Pythonic”的方式来做同样的事情:
你甚至可以将它变成一个单行:
不过我一开始会避免这条路线......它的可读性要差得多!
As several people have said, your code appears to work perfectly. Perhaps your "data.txt" file is in a different directory than your current working directory (not necessarily the directory that your script is in)?
However, here's a more "pythonic" way of doing the same thing:
You could even make it a one-liner with:
I'd avoid that route at first though... It's much less readable!
你如何运行该程序?您确定 data.txt 有数据吗?文件中是否有空行?
试试这个:
How are you running the program? Are you sure data.txt has data? Is there an empty line in the file?
try this: