Python if else 语句未通过或未读取 txt

标签 python text

我正在计算文件“Index40”中的行数。有 11,436 行。我将该数字作为字符串保存在 txt 文件中。我想要我的代码做的是每晚计算这个文件中的行数,如果等于作为单个字符串值存储的数字我希望脚本结束,否则重写文本文件中的数字并继续剧本。我遇到的问题是脚本总是认为行数不等于 txt 值。这是代码:

lyrfile = r"C:\Hubble\Cimage_Project\MapData.gdb\Index40"
result = int(arcpy.GetCount_management(lyrfile).getOutput(0))
textResult = str(result)
with open(r'C:\Hubble\Cimage_Project\Index40Count.txt', 'r+') as a:
    if a == textResult:
        pass  
    else:
        a.write(textResult)
        #then do a bunch more code
        print "not passing"

最佳答案

您似乎是在将 textResulta 进行比较,后者是 文件对象

如果你想要文件的内容,你需要从文件对象中读取,例如a.read() 以字符串形式获取文件的全部内容。

所以我认为您正在寻找这样的东西:

with open(r'C:\Hubble\Cimage_Project\Index40Count.txt', 'r+') as a:
    contents = a.read() # read the entire file
    if contents != textResult:
        a.seek( 0 ) # seek back to the beginning of the file
        a.truncate() # truncate in case the old value was longer than the new value
        a.write(textResult)
        #then do a bunch more code
        print "not passing"

关于Python if else 语句未通过或未读取 txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20005148/

相关文章:

python - Scrapy 请求堆栈溢出

c# - 如何在 C# 中将 HTML 转换为文本?

c# - 如何将字符串转换为具有 unix 行结尾的字节?

text - 使用 CSS 3 的浅色文本阴影

python - 使用 Python 的分配算法

python - NameError: name '' is not defined, trying to make a to-do list CLI 应用程序

Python 3.x 请求使用 unicode 字符进行重定向

python - 如何制作一组既可以同步又可以异步使用的函数?

python - 使用 python 解析具有异常分隔符的文本文件

python - 使用Python+PIL或Imagemagick创建文本蒙版