Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.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_File Handling - Fatal编程技术网

编写和编辑文件(Python)

编写和编辑文件(Python),python,file-handling,Python,File Handling,首先,我想道歉,因为我是Python的初学者。不管怎样,我有一个Python程序,可以用一般形式创建文本文件: Recipe Name: Item Weight Number of people recipe serves 我想做的是让程序能够检索配方,并为不同数量的人重新计算配料。程序应输出配方名称、新人数和新人数的修订数量。我能够检索配方并输出配方,但我不确定如何为不同数量的人重新计算成分。这是我代码的一部分: def modify_recipe(): Choice_Exist =

首先,我想道歉,因为我是Python的初学者。不管怎样,我有一个Python程序,可以用一般形式创建文本文件:

Recipe Name:
Item
Weight
Number of people recipe serves
我想做的是让程序能够检索配方,并为不同数量的人重新计算配料。程序应输出配方名称、新人数和新人数的修订数量。我能够检索配方并输出配方,但我不确定如何为不同数量的人重新计算成分。这是我代码的一部分:

def modify_recipe():
    Choice_Exist = input("\nOkaym it looks like you want to modify a recipe. Please enter the name of this recipe ")
    Exist_Recipe = open(Choice_Exist, "r+")
    time.sleep(2)
    ServRequire = int(input("Please enter how many servings you would like "))

因为我使用的是Python 2.7.5,所以我不得不对其进行了几次编辑,但这应该是可行的:

import time

def modify_recipe():
    Choice_Exist = input("\nOkay it looks like you want to modify a recipe. Please enter the name of this recipe: ")
    with open(Choice_Exist + ".txt", "r+") as f:
        content = f.readlines()
        data_list = [word.replace("\n","") for word in content]

    time.sleep(2)

    ServRequire = int(input("Please enter how many servings you would like: "))

    print data_list[0]
    print data_list[1]
    print int(data_list[2])*ServRequire #provided the Weight is in line 3 of txt file
    print ServRequire

modify_recipe()

我建议将您的工作分成多个步骤,然后依次完成每个步骤(进行研究、尝试编写代码、提出具体问题)

1) 抬头看。1.a)尝试重新创建您找到的示例,以确保您理解每段代码的功能。1.b)编写自己的脚本,仅完成所需程序的这一部分,即打开现有配方文本文件或创建新的配方文本文件

2) 在Python中真正使用自己的函数,尤其是传递自己的参数。你想做的是一个好的“”的完美例子,如果你正确的话,一个函数读取一个输入文件,另一个函数写入一个输出文件,另一个函数提示用户输入他们想要的倍数,等等

3) 为用户输入添加
try/except
块。如果用户输入非数字值,这将允许您捕获该值并再次提示用户输入更正的值。比如:

while True:
  servings = raw_input('Please enter the number of servings desired: ')
  try:
    svgs = int(servings)
    break
  except ValueError:
    print('Please check to make sure you entered a numeric value, with no'
        +' letters or words, and a whole integer (no decimals or fractions).')
或者,如果希望允许小数,可以使用
float()
而不是
int()

4) [半高级]基本正则表达式(又名“regex”)将非常有助于构建您正在制作的内容。听起来您的输入文件将具有严格的、可预测的格式,因此可能不需要正则表达式。但是,如果您希望接受非标准的配方输入文件,regex将是一个很好的工具。虽然学习这项技能可能有点困难或令人困惑,但有很多很好的教程和指南。我过去收藏的一些是,和。在学习构建自己的正则表达式模式时,我强烈推荐一个很棒的工具是(或者类似的工具之一),它可以告诉您模式的哪些部分在工作,哪些部分不工作,以及为什么

这里有一个提纲可以帮助您开始:

def read_recipe_default(filename):
  # open the file that contains the default ingredients

def parse_recipe(recipe):
  # Use your regex to search for amounts here. Some useful basics include 
  # '\d' for numbers, and looking for keywords like 'cups', 'tbsp', etc.

def get_multiplier():
  # prompt user for their multiplier here

def main():
  # Call these methods as needed here. This will be the first part 
  #  of your program that runs.
  filename = ...
  file_contents = read_recipe_file(filename)
  # ...

# This last piece is what tells Python to start with the main() function above.
if __name__ == '__main__':
  main()

开始可能很艰难,但最终它是非常值得的!祝你好运

你有什么问题?你没有说什么。你看了python教程的一节了吗?我不知道如何允许用户通过输入所需的份数来乘以原始份数,因为默认份数在文本文件中。有人知道如何做到这一点吗?我不熟悉文件处理,一直在不断地研究,但没有结果。您可以将文件读入字典或列表,修改它并覆盖现有文件读取文件,解析内容,转换数字
int
/
float
(就像您在代码的最后一行所做的那样),使用
*
乘以数字,将它们转换回字符串并重写文件。关于这些步骤中的任何一个都有很多问题。解析内容?你能提供一个示例代码吗?谢谢!这是可行的,但这部分代码的作用是什么?使用open(选项_Exist+“.txt”,“r+”)作为f:content=f.readlines()data_list=[word.replace(“\n”,”)for word in content]打开前一行中输入的配方文本文件,并将每一行读入列表
content
。在此列表中,列表中的每个条目后面都有“换行符”(
\n
)。所以
data\u list
删除了所有这些不需要的
\n
字符。@Maxine123如果我的代码有效,你能接受我的答案吗?:)(按绿色复选标记)提前感谢!