Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在文本文件中的单词前添加数字?_Python_Python 3.x - Fatal编程技术网

Python 如何在文本文件中的单词前添加数字?

Python 如何在文本文件中的单词前添加数字?,python,python-3.x,Python,Python 3.x,我在文本文件中有此菜单: #菜单1文件 水母怡生梨 鱼汤海鲜干 清蒸海水石斑鱼 我有这个密码: menuList = input('enter number:') def printPackage(menuList): if menuList == '1': with open('menu/Menu1.txt')as f: data = f.read() print(data) printPackage(menuList)

我在文本文件中有此菜单:

#菜单1文件
水母怡生梨
鱼汤海鲜干
清蒸海水石斑鱼
我有这个密码:

menuList = input('enter number:')
def printPackage(menuList):
    if menuList == '1':
        with open('menu/Menu1.txt')as f:
            data = f.read()
            print(data)
printPackage(menuList)
我应该向我的代码中添加什么,以便我可以像这样打印文本文件

---------
菜单列表
---------
1水母怡生梨
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
甚至更短:

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)]
只有一行(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)]

迭代文件行并使用
枚举
获取索引。感谢您的帮助和解释。帮助很多如果我只想要文本文件中的特定字行,我应该对程序做什么更改?例1。A 2。文本文件中的B3.C…如何仅获取1。A或1.A和2.C,其中C变为数字2
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)]