2017-11-15 11 views
-1

私は、テキストファイル内のこのメニューを持っている:テキストファイル内の単語の前に数字を追加するにはどうすればよいですか?

#Menu 1 file 
Jelly Fish Yee Sang with Pear 
Dried Seafood with Fish Soup 
Steamed Sea Water Grouper 

、私はこのコードを持っている:私はこのように印刷するには、私のテキストファイルを持っているように、

menuList = input('enter number:') 
def printPackage(menuList): 
    if menuList == '1': 
     with open('menu/Menu1.txt')as f: 
      data = f.read() 
      print(data) 
printPackage(menuList) 

は、私は自分のコードに何を追加する必要がありますか?

--------- 
Menu List 
--------- 
1. Jelly Fish Yee Sang with Pear 
2. Dried Seafood with Fish Soup 
3. Steamed Sea Water Grouper 

お願いします。

+0

ファイル行を反復し、インデックスを取得するために 'enumerate'を使います。 –

答えて

2
menuList = input('enter number:') 
def printPackage(menuList): 
    if menuList == '1': 
     with open('menu/Menu1.txt')as f: 
      lines = [] 
      for l_i, line in enumerate(f.read().split('\n'), 1): # Read the file and split it on newline. Enumerate the results returning index (l_i) and the line. Start l_i at 1 
       formatted_line = '%s. %s' % (l_i, line) # Format it with the line number. 
       print(formatted_line) 
       lines.append(formatted_line) 

      # If you want to save it. 
      with open('menu/Menu1_with_numbers.txt', 'w') as o_f: 
       o_f.write('\n'.join(lines)) # Join back the lines on newline and write it out to Menu1_with_numbers.txt 
+1

ヘルプと説明をありがとう。たくさんの助けがあります –

+0

テキストファイルの中に特定の単語行だけを入れたいのであれば、プログラムを変更する必要はありますか?例があります1. 2.テキストファイル内のB 3.C ....どのように取得する1. Aまたは1.Aと2.C Cが2に変更する –

0

このPython的WAYを(ずっと速く)してみてください。

get_input = input('Enter Number: ') 
if not get_input == "1": 
    exit() 
write_save = open("menu/result.txt", "a") 
read_lines = [write_save.write("{}. {}{}".format(counts, line.rstrip("\n"), "\n")) for counts, line in enumerate(open('menu/Menu1.txt'), 1)] 
write_save.close() 

あるいは短い:

get_input = input('Enter Number: ') 
if not get_input == "1": 
    exit() 
read_lines = [open("result.txt", "a").write("{}. {}{}".format(counts, line.rstrip("\n"), "\n")) for counts, line in enumerate(open('Menu1.txt'), 1)] 

JUST ONE LINE(LOOL)

if input("Enter Number: ") == "1" : [open("result.txt", "a").write("{}. {}{}".format(counts, line.rstrip("\n"), "\n")) for counts, line in enumerate(open('Menu1.txt'), 1)] 
+0

@Joehan:投票なし!しかし、これらも試してみてください... XD – DRPK

関連する問題