python编程 - 从多个文件中读取

时间:2016-02-10 02:08:34

标签: python python-2.7

您好我的大学任务要求我们创建一个

的python程序
  1. 要求用户输入三个包含单词的文件名,格式为file1 file2 file3,其中每个文件名用空格分隔。此输入分配给变量FList
  2. 该计划将FList拆分为三个文件名file1file2file3
  3. 对于FList中的每个文件,程序会读取文件中的字词,并将这些字符串存储到各自的列表中:wordList1wordList2wordList3。例如,file1中的字词将分配给wordList1
  4. 程序要求用户输入搜索词并将其分配给searchWord
  5. 该计划会在wordList1wordList2wordList3中搜索searchWord,并计算每个文件中的匹配数,并将结果分配给各自的变量:{ {1}},file1Resultsfile2Results
  6. file3Results

    我在我的桌面上创建了三个.txt文件,名为Flist=raw_input("Please enter the three filenames seperated by spaces") Flist=Flist.split() file1=open(Flist[0],"r") wordList1=file1.read().split() file1.close() file2=open(Flist[1],"r") wordList2=file2.read().split() file2.close() file3=open(Flist[2],"r") wordList3=file3.read().split() file3.close() searchWord=raw_input("Which word would you like to search ") file1Results=wordList1.count(searchWord) file2Results=wordList2.count(searchWord) file3Results=wordList3.count(searchWord) print "file1Results=",file1Results print "file2Results=",file2Results print "file3Results=",file3Results output.txtoutput2.txt但由于某种原因,当我测试运行该程序时,它说{{1} }不存在。

2 个答案:

答案 0 :(得分:0)

我无法告诉您的输入是什么,但听起来您正在寻找错误目录中的文件。

f1 = open('output1.txt')

将搜索正在运行python脚本的文件夹中的输出。 您可能需要的是这样的事情:

desktop_path = 'C:/Users/YOURNAME/Desktop/'
f1 = open(desktop_path + 'output1.txt') # open(desktop_path + Flist[0])

此外,可能存在的问题是

Flist.split() 

的工作原理如下:

  

例如,' 1 2 3' .split()返回[' 1',' 2',' 3']和' 1 2 3' .split(无,1)返回[' 1',' 2 3']。

您可以在此here找到更多信息。

答案 1 :(得分:0)

我建议你添加

Building

到脚本的开头并运行它;它会告诉你当前正在使用的目录。

如果我在桌面上保存脚本并通过双击运行它,它将以import os print(os.getcwd()) 作为当前目录运行。我怀疑你的情况是这样的,你恰好在该目录中有一个名为c:\windows\system32的文件。

如果是这种情况,您可以使用output.txt使其显示在正确的位置。