Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.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 read.index()似乎读取了错误的索引?_Python - Fatal编程技术网

Python read.index()似乎读取了错误的索引?

Python read.index()似乎读取了错误的索引?,python,Python,所以我花了几天的时间在这上面,我想不出答案。但我已经把问题简化成我认为最简单的形式。我试图在一个文件中找到两个不同的字符串,并读取它们之间的文件部分。现在我有一个测试文件,里面只有123456789,等等。我正在运行以下代码: with open('Testing.txt', 'r') as file: read = file.read() if "4" in read: begin = read.index("4") print begin

所以我花了几天的时间在这上面,我想不出答案。但我已经把问题简化成我认为最简单的形式。我试图在一个文件中找到两个不同的字符串,并读取它们之间的文件部分。现在我有一个测试文件,里面只有123456789,等等。我正在运行以下代码:

with open('Testing.txt', 'r') as file:
   read = file.read()
   if "4" in read:
        begin = read.index("4")
        print begin
        if "8" in read:
            end = read.index("8")
            file.seek(begin)
            print "The location to begin reading is", file.tell()
            data= file.read()[begin:end]
            print "data =", data
如果我从1开始,代码工作正常。如果我从2以上的某个位置开始,它会将数字拉到列表的较低位置。我有点不明白为什么会这样。我希望我说的有道理

一旦创建file.seekbegin,file.read将从开始而不是从文件开始读取文件

因此,要么创建file.seek0,要么更改计算数据的方式:data=file.read[:end-begin]

但是为什么要第二次读取文件,因为在读取变量中已经有了文件内容。只要做:

data = read[begin:end]
此外:

您可以使用正则表达式或拆分函数来代替计算索引

避免使用read作为变量名,因为这会使习惯于在打开的文件上使用read的读者感到困惑


非常感谢你!我真不敢相信我竟然如此愚蠢!