[英]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.