簡體   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