【问题标题】:readlines is showing up empty after creating file创建文件后,readlines 显示为空
【发布时间】:2014-06-13 17:28:44
【问题描述】:

我希望创建一个文件,然后读取我刚刚放入其中的值并将这些值放入列表中。我使用 readlines 来执行此操作,但是我得到“列表分配索引超出范围”错误,告诉我它没有读取文件。

这是我的代码:

import os

class open_saved_file():

    def __init__(self):
        self.path = os.getcwd()
        self.path_extension = "/Saved_Paths"
        self.file_extension = "/Paths.txt"
        self.paths = []

    def test_path(self):

        test_bool = os.path.exists(self.path+self.path_extension)
#1) path does not exist
        if not test_bool:
            print "The start folder does not exist, let's create it"
            os.makedirs(self.path+self.path_extension)
            print "just made file, now make Paths.txt"
            of = open(self.path+self.path_extension+self.file_extension, 'w+')
            print "Lets add 4 dummy lines of code"
            i = 0
            while i < 4:
                of.write("dummy\n")
                i = i+1
            print "just added four lines of dummy"
            of.close()
            print "lets test"
            self.read_lines_into_list()
            return self.paths
#2) path and file exist
        else:
            print "The start folder did exist, yay!"
            print "lets open it and put its value into paths list"
            self.read_lines_into_list()
            return self.paths

    def read_lines_into_list(self):
        of = open(self.path+self.path_extension+self.file_extension)
        lines = of.readlines()
        self.paths[0] = lines[0][:-1]
        self.paths[1] = lines[1][:-1]
        self.paths[2] = lines[2][:-1]
        self.paths[3] = lines[3][:-1]
        print "lets test if all the values went in"
        j = 0
        while j < 4:
            print self.paths[j]
            i = i+1

【问题讨论】:

  • 您确认文件确实是在您指定的位置创建的吗?
  • 是的,我有。它是在抛出错误之前创建的
  • 在您的帖子中包含错误。

标签: python readlines


【解决方案1】:

发生错误不是因为lines 为空,而是因为self.paths 为空。而不是:

self.paths[0] = lines[0][:-1]

使用append():

self.paths.append(lines[0][:-1])

您的while 循环中也会出现错误,因为当您的循环变量为j 时,您正在执行i = i+1。您可以简单地将i 替换为j,或者更好的是,使用for 循环:

for path in self.paths:
    print path

【讨论】:

    【解决方案2】:

    您还可以添加对 os.path.isfile 的调用以验证文件是否存在。

    【讨论】:

      【解决方案3】:

      这里是修改后的代码。

      import os
      class OpenSavedFile():
      def __init__(self):
          self.path = os.getcwd()
          self.path_extension = "/Saved_Paths"
          self.file_extension = "/Paths.txt"
          self.paths = []
      
      def test_path(self):
          test_bool = os.path.exists(self.path+self.path_extension)
          if not test_bool:
              print "The start folder does not exist, let's create it"
              os.makedirs(self.path+self.path_extension)
              print "just made file, now make Paths.txt"
              of = open(self.path+self.path_extension+self.file_extension, 'w+')
              print "Lets add 4 dummy lines of code"
              i = 0
              while i < 4:
                  of.write("dummy\n")
                  i = i+1
              print "just added four lines of dummy"
              of.close()
              print "lets test"
              self.read_lines_into_list()
              return self.paths
          else:
              print "The start folder did exist, yay!"
              print "lets open it and put its value into paths list"
              self.read_lines_into_list()
              return self.paths
      
      def read_lines_into_list(self):
          of = open(self.path+self.path_extension+self.file_extension)
          lines = of.readlines()
          # lines is not empty 
          # remove the comment below and see
          # print lines
          for line in lines:
              self.paths.append(line[:-1]) # paths is an empty list so append the contents
          print "lets test if all the values went in"
          j = 0
          while j < 4:
              print self.paths[j]
              j += 1 # this is not i += 1
      
      op = OpenSavedFile()
      op.test_path()
      

      【讨论】:

      • 作者原代码并没有无限迭代列表,所以这是不正确的。到达i = i+1 时,会抛出UnboundLocalError 并退出程序。
      • 是的,j 在整个迭代过程中的值为 0,因此将抛出 UnboundLocalError
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多