我正在寻找创建一个文件,然后读取我刚刚放入其中的值并将这些值放入列表中。我使用 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