2011-11-16 208 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:\'是不是你认为它是。