さて、私は一連のことをするプログラムに取り組んでいます。まず、2つの外部ファイルの内容を読み込み、そのファイルの各行をリストに変換し、それらの2つのリストを1つのリストに結合します。Pythonのリスト項目から空白と改行文字を取り除く
各ファイルは、その前にエントリ番号が付いた名前のリストであり、その後に新しい行があります。したがって、各ファイルには、そうのようにフォーマットされた100〜200エントリのリストです:
1. Michael \n
2. Ben \n
3. Ken \n
4. David \n
ので、プログラムがリストにそれぞれの行を読み込み、その後、ファイルを開きます。
ここで私の問題が発生しています。私は、各行からエントリ番号、空白、改行コマンドを取り除く必要があります。
私はaline.aplit(」 ')を使用していますように、各ラインのために:
1. Michael \n
になるでしょう: [' 1。 '、' Michael \ n ']
ここからは、' \ n 'を取り除き、[1]をこのファイルの名前のリストに追加するだけでよいはずです。
これは私がエラーになっているところです。具体的には:ここ
Traceback (most recent call last): File "H:/ITP100/assignments/Chapter 7/Names-3.py", line 30, in entry1 = value_xy.rstrip('\n') AttributeError: 'list' object has no attribute 'rstrip'
は完全なコードである:コード上
Name1 = (input("Enter a name: "))
file_xy = open("BoyNames.txt", "r")
list_xy = []
file_xx = open("GirlNames.txt", "r")
list_xx = []
test_boys =[]
test_girls =[]
entry1 = []
for aline in file_xy:
value_xy = aline.split(' ')
entry1 = value_xy.rstrip('\n')
test_boys.append[1]
#entry2 = entry1[1].strip()
list_xy.append(entry1[1])
for aline in file_xx:
value_xx = aline.split(' ')
entry_xx1 = value_xx.rstrip('\n')
test_girls.append(entry_xx1)
# entry_xx2 = value_xx[1].lstrip()
list_xx.append(entry_xx1)
#print(list_xy)
names = list_xy + list_xx
print("This is the list \'names\'. This is the combined list of all names."+'\n'+str(names))
print("This is the list \'test_boys\'. This is the post-stripping list of boy names."+'\n'+str(test_boys))
print("This is the list \'test_girls\'. This is the post-stripping list of girl names."+'\n'+str(test_girls))
if Name1 in names:
print(Name1+" is in the list.")
else:
print(Name1+" is not in the list.")
このように 'with open'メソッドを使用する場合、ファイルを読み込んだり書き込んだりする天気を伝える必要はありませんか? –
いいえ、あなたは '' r "'、 '' w "'などのパラメータを指定することができます。この機能はファイルが 'with open'ブロックの直後に自動的に閉じられることを覚えておく必要はありませんあなたのファイルが開いているか閉じていますか? – MaximTitarenko
Cool知っておいてよかった。 これで、この行に範囲外のエラーが発生しました。 name = line.strip()。split()[1] –