2011-11-16 136 views
-1

我正在編寫一個程序來讀取5個文件中的文本行,並將這5個文件中的文本編譯到相應的列表中。從文件中讀取行

但是我有麻煩讓程序實際讀取文本列表很大,這是我到目前爲止的代碼:

from random import random 

from dice import choose 

b = open ('E:\Videos, TV etc\Python\ca2\beginning.txt', 'r'). readlines() 
stripped_b = [item.strip() for item in b] 

a = open ('E:\Videos, TV etc\Python\ca2\adjective.txt', 'r'). readlines() 
stripped_a = [item.strip() for item in a] 

i = open ('E:\Videos, TV etc\Python\ca2\inflate.txt', 'r'). readlines() 
stripped_i = [item.strip() for item in i] 

n = open ('E:\Videos, TV etc\Python\ca2\noun.txt', 'r'). readlines() 
stripped_n = [item.strip() for item in n] 

phrase = [] 

turn = 0 

def business_phrase(x): 

    x = raw_input("\n\nInsert a number of business phrases to generate: ") 
    while turn <= x: 
     turn += 1 
     for item in stripped_b: 
      random_word = choose(item) 
      phrase.append(random_word) 
     for item in stripped_a: 
      random_word = choose(item) 
      phrase.append(random_word) 
     for item in stripped_i: 
      random_word = choose(item) 
      phrase.append(random_word) 
     for item in stripped_n: 
      random_word = choose(item) 
      phrase.append(random_word) 
    print random_list 

business_phrase(X)

哪裏開始,形容詞,膨脹和名詞是文本文件,骰子是一個包含選擇函數的python文件。

我運行這個程序,試圖生成一個短語,我得到了以下錯誤消息:

IOError: [Errno 22] invalid mode ('r') or filename 'E:\\Videos, Tv etc\\Python\\ca2\\x08eginning.txt' 

我不知道爲什麼,因爲他們是在同一個目錄,因爲它不會讀取文本文件(事實上​​與包含該功能的程序在同一個目錄中)。

沒有人有我完全難倒任何想法。

+0

你讀過錯誤了嗎?不,你真的*讀過嗎? –

+0

是的,但我不知道它是什麼意思,我是一個完整的初學者。 –

+0

'\ x08'沒有發出任何警告鈴聲? –

回答

3

'\' 用於在Python字符串逃脫。 Here's a list of what you can do with them。你想逃避反斜槓來讓它們看起來像背板,這意味着使用其中的兩個。這樣做:

'E:\\Videos, TV etc\\Python\\ca2\\adjective.txt' 

Raw strings like larsmans suggested也將工作!

+0

我改變了它,但現在我得到了像以前一樣+語法錯誤。我很困惑! –

+0

什麼是錯誤信息?請複製粘貼! – Michal

+0

它與問題中提到的相同,但是它在下一行中有SyntaxError:無效語法。 :( –

2

不,你可能有在它^ h的文件名。逃避你的反斜槓。

'...\\...' 
8

處理Windows路徑名時,總是使用原始字符串字面量:

r'E:\Videos, TV etc\Python\ca2\beginning.txt' 

,因爲否則的反斜槓可以被解釋爲開始一個轉義序列。

另外,注意用在字符串的結尾反斜線:r'C:\'是不是你認爲它是。