繁体   English   中英

python编程-从多个文件读取

[英]python programming-reading from multiple files

嗨,我遇到了大学作业的麻烦,要求我们创建一个python程序

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

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  

我已经在桌面上制作了三个.txt文件,分别名为output.txtoutput2.txtoutput3.txt但是由于某种原因,当我测试运行该程序时,它说output2.txt不存在。

我不能说出您的输入是什么,但是听起来您在错误的目录中寻找文件。

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(None,1)返回['1','2 3' ]。

您可以在这里找到更多信息

我建议你添加

import os

print(os.getcwd())

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

如果我将脚本保存在桌面上并通过双击运行它,则它将以c:\\windows\\system32作为当前目录运行。 我怀疑您的操作与此相同,并且您在该目录中碰巧有一个名为output.txt的文件。

在这种情况下,可以使用os.path.join(r"path\\to\\desktop\\", filename)使其在正确的位置显示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM