【问题标题】:python programming-reading from multiple filespython编程——读取多个文件
【发布时间】:2016-02-10 02:08:34
【问题描述】:

您好,我在大学作业中遇到问题,要求我们创建一个 python 程序

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

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 不存在。

【问题讨论】:

  • 我在您的代码中看不到任何会导致您提到的错误的内容。你确定你没有在文件名中打错字(在实际的文件系统中,或者当你将文件名提交给 Python 程序时)?你能显示异常的回溯吗?
  • 应该是Flist=Flist.split(" ")吗?
  • 您的程序在哪个目录中,相对于您的 .txt 文件,以及您如何在命令行中引用 .txt 文件?
  • ...如果您输入output.txt output.txt output.txt 会发生什么?它抱怨那个文件吗?
  • @White .split() 默认会在空白处分割。

标签: python python-2.7


【解决方案1】:

我不知道你的输入是什么,但听起来你在错误的目录中寻找文件。

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 ']。

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

【讨论】:

  • ...但他没有得到 output.txt 的任何错误,大概在同一目录中?
  • 正确。我正在添加可能是问题的第二部分,但因为我不知道输入或输出。我只是列出最好的猜测。
【解决方案2】:

我建议你添加

import os

print(os.getcwd())

到脚本的开头并运行它;它会告诉你当前工作的目录。

如果我在桌面上保存脚本并通过双击运行它,它会以c:\windows\system32 作为当前目录运行。我怀疑你的也在做同样的事情,而你恰好在那个目录中有一个名为 output.txt 的文件。

如果是这种情况,您可以使用os.path.join(r"path\to\desktop\", filename) 使其位于正确的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多