簡體   English   中英

從文件讀取行

[英]Reading lines from a file

我正在編寫一個程序,以從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)

其中,開頭,形容詞,膨脹和名詞是文本文件,而dice是包含選擇功能的python文件。

我運行該程序嘗試生成一個短語,然后收到以下錯誤消息:

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

我不知道為什么它不讀取文本文件,因為它們位於與所述相同的目錄中(實際上與包含該函數的程序位於同一目錄中)。

有誰有任何想法讓我完全迷住了。

處理Windows路徑名時,請始終使用原始字符串文字:

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

因為否則反斜杠可以解釋為開始轉義序列。

另外,請注意在字符串末尾加反斜杠: r'C:\\'不是您認為的那樣。

'\\'用於Python字符串中的轉義。 這是您可以使用它們執行的操作的列表 您想轉義反斜杠以使其實際上讀作反斜杠,這意味着要使用其中的兩個。 做這個:

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

建議使用像larsmans這樣的原始字符串也可以!

不,您可能沒有一個帶有^ H的文件名。 轉義您的反斜杠。

'...\\...'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM