因此代码非常简单,如果用户没有输入可行的文件,那么程序会关闭,但是当我试图将打开的文件从open_file()函数移动到main时函数,然后在read_file()函数中使用它。然而,当我打印它来测试它时,它打印的不仅仅是第一行......我只是试图抓住第二行用逗号分隔的第四个单词。
#opens the file for data
def open_file():
input_file = input("Enter a food crop file: ")
try:
f1 = open(input_file,"r")
next(f1)
except FileNotFoundError:
print("File not found; terminating program.")
return False,False
input_file2 = input("Enter a non-food crop file: ")
try:
f2 = open(input_file2,"r")
next(f2)
except FileNotFoundError:
print("File not found; terminating program.")
return False,False
return f1,f2
def read_files(f1,f2):
line1 = f1.readline()
list_line1 = line1.replace(',','').split()
product1 = list_line1[3]
line2 = f2.readline()
list_line2 = line2.replace(',','').split()
product2 = list_line2[3]
print(product1,product2)
return product1,product2
#main fucntion, will call all other functions
def main():
f1,f2 = open_food_file()
while f1 != False:
product1,product2 = read_files(f1,f2)
#launches code
main()
看起来应该是这样的
Enter a food crop file: file_name.csv
Enter a non-food crop file: file_name.csv
product1 = 4th item in list for file1 here
product2 = 4th item in list for file2 here
它返回此信息,但随后
出错File "C:/COLLEGE/CSE/CSE 231/Code/redo.py", line 28, in read_files
product1 = list_line1[3]
IndexError: list index out of range