如何纠正这个for循环代码?

时间:2012-12-15 12:35:03

标签: for-loop python-2.7 performance

# Define the project name and path for input files
# need to use \ before \t and \ to print these characters
Project = "101"
path_Directory =  "C:\Users\\tp\Desktop\project\\"
full_path_Directory = path_Directory + Project

# Set path for files in the program
File_stock = full_path_Directory + "_stock.txt"
File_exchange = full_path_Directory + "_exchange.txt"
File_country = full_path_Directory + "_country.txt"

var_set = [File_stock, File_exchange, File_country]

  for var in var_set:
    var = open(var,'r')
    var = var.read()[3:]
    print var

我创建了一个包含3个变量的var_set - File_stock,File_exchange和File_country,因为我认为循环重复任务会更有效。虽然上面显示的代码的输出是正确的,但是当我键入:“print stock”或“print exchange”或print“country”时,输出总是错误的,因为它显示路径目录而不是文本文件中的数据

有谁知道可能是什么原因以及我该如何解决?

1 个答案:

答案 0 :(得分:3)

如果要将每个文件数据存储在数据结构中,则需要使用dict或类似的方法来执行此操作:

Project = "101"

path_Directory =  r"C:\Users\tp\Desktop\project"
names = ['stock', 'exchange', 'country']
data = {}

for name in names:
    path = os.path.join(path_Directory, '{0}_{1}.txt'.format(Project, name))
    data[name] = open(path, 'r').read(3)

我还将.read()[:3]替换为.read(3),只读了三个字符而不是读取整个文件;它效率更高。

现在data将有三个键,每个键指向从每个文件中读取的3个字符:

print data['stock']  # prints 'xyz'. etc.