0
# 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

我创建了一个 var_set 来包含 3 个变量 - File_stock、File_exchange 和 File_country,因为我认为循环执行重复性任务会更有效。虽然上面显示的代码的输出是正确的,但是当我输入:“打印股票”或“打印交换”或打印“国家”时,输出总是错误的,因为它显示的是路径目录而不是文本文件中的数据.

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

4

1 回答 1

3

如果要将每个文件的数据存储在数据结构中,则需要使用 adict或类似方法:

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.
于 2012-12-15T13:11:09.963 回答