[英]python programming-reading from multiple files
嗨,我遇到了大学作业的麻烦,要求我们创建一个python程序
file1
file2
file3
,其中每个文件名用空格分隔。 此输入分配给变量FList
。 FList
分成三个文件名file1
, file2
和file3
。 FList
每个文件,程序都会从文件中读取单词,并将这些字符串存储到它们各自的列表中: wordList1
, wordList2
和wordList3
。 例如,来自file1
单词将分配给wordList1
。 searchWord
。 wordList1
, wordList2
和wordList3
搜索searchWord
,并计算每个文件中的匹配数,并将结果分配给它们各自的变量: file1Results
, file2Results
和file3Results
。 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.txt
, output2.txt
, output3.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.