Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.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中将.txt文件传递给函数?_Python_String_Function_File_Tuples - Fatal编程技术网

如何在Python中将.txt文件传递给函数?

如何在Python中将.txt文件传递给函数?,python,string,function,file,tuples,Python,String,Function,File,Tuples,我被要求创建一个函数,该函数接受一个字符串参数,创建并返回一个元组,其中包含由字符串指定的人的详细信息(例如,名字、第二个名字和薪水)。字符串带有一个布局:名字、第二个名字、薪水。然后,我必须创建另一个函数,该函数将元组作为参数,并使用此布局在一行固定宽度字段中打印关于此人的详细信息:薪水、名字、第二个名字。值得一提的是,字符串必须取自用户提供的文件输入。这就是我所尝试的: file = input('Insert a file:') try: fin = open(file) exc

我被要求创建一个函数,该函数接受一个字符串参数,创建并返回一个元组,其中包含由字符串指定的人的详细信息(例如,名字、第二个名字和薪水)。字符串带有一个布局:名字、第二个名字、薪水。然后,我必须创建另一个函数,该函数将元组作为参数,并使用此布局在一行固定宽度字段中打印关于此人的详细信息:薪水、名字、第二个名字。值得一提的是,字符串必须取自用户提供的文件输入。这就是我所尝试的:

file = input('Insert a file:')

try:
    fin = open(file)
except IOError as a:
    fin = None
    print('Failed to open', file)

def person(fin):
    my_str = open('fin', 'r').read()
    print(tuple(my_str))

任何形式的帮助都将不胜感激,因为我完全迷路了。提前谢谢你。

就在我的头顶上,fin是一个变量,但你可以将它作为纯文本字符串传递

    my_str = open(fin, 'r').read()

您需要在
try
语句中写入
fin=open(file,“wt”)
。结尾处的
wt
表示您使用文本编写(也可以用二进制编写)

稍后您需要将
my_str=open(fin,'r')
放入,因为
fin
是一个对象,而不是实际文件的名称

import argparse

def my_func(my_file): 
    with open(my_file_name, 'r') as f_obj:
        # do stuff with f_obj, like f_obj.read()

parser = argparse.ArgumentParser()
parser.add_argument('--infile', type=str, help='Name of file to read', required=True)
options = parser.parse_args()
input_file_name = options.infile

my_func(input_file_name)

让我们将此任务转换为许多小的、更容易解决的任务

第一功能 此函数接受一个字符串,并在空白处将其拆分,然后返回一个元组。请注意,没有进行错误检查。稍后,您应该检查输入是否有效

第二功能 在这里,您将一个元组连接回一个字符串。在加入之前,您需要将每个项目转换为字符串(
str(i)

从文件中读取 阅读时,你应该使用。这样可以确保不再使用文件时,该文件始终处于关闭状态

打开文件: 文件的路径必须是相对于当前工作目录(脚本所在的目录)或绝对路径

文件和路径之间的差异 文件的路径(
路径到文件
)与实际打开的文件(
文件
)之间存在差异。用户可以输入路径,您必须使用它来打开文件。用户无法输入文件对象

>>> type(path_to_file)
<class 'str'>
>>> type(file)
<class '_io.TextIOWrapper'>
如果您对某个部分有任何问题,欢迎您在评论中提出

编辑 基于文件内容的调整 文件中的一行是:切尔西右后卫扎帕科斯塔20000000

您需要展开元组:

原件:
姓名、姓氏、工资

新增:
团队、职位、名字、姓氏、薪水

注意:现在只需将工资作为s字符串,而不是将其转换为int或float

原件:
返回姓、名、整数(工资)

新增:
返回团队、职位、名字、姓氏、薪水

原始:
string\u person=”“.join(str(i)表示i-in-person\u元组)

新增:
string\u person=”“.加入(person\u元组)

资源
  • 应该是如何解决错误的提示。如果这没有帮助,请发布您要读取的文件的内容

您是否希望将文件名传递给程序?还是函数?
open('fin',r')
部分没有意义,因为您可能没有名为'fin'的文件,但变量fin中有一个已打开的文件对象。@fiacre我必须在程序中打开该文件,然后将其传递给函数#1,该函数将内容作为字符串,然后将其转换为元组。然后函数#2必须在一行上的固定宽度字段中输出元组的内容。@MichaelButscher是的,您是正确的。我尝试使用open(fin,'r'),但它给了我一个错误。即使我尝试这样做,它也会给我一个错误:TypeError:预期的str、bytes或os.PathLike对象,而不是_io.TextIOWrapperfin是已打开以供读取的文件缓冲区。不要再打开它了--没有意义。他在读文件--不是在写。不需要“wt”,只需“w”即可。fin是一个文件对象,不是变量。谢谢您的帮助。程序给出了输出,但也返回了一个错误:回溯(最近一次调用last):文件“C:/Users/abc/Desktop/test.py”,第39行,在tuple\u person=string\u to\u tuple(line)文件“C:/Users/abc/Desktop/test.py”,第11行,在string\u to\u tuple first\u name,last\u name,salary=person\u string.split(“”)中ValueError:太多的值无法解包(预期为3)好的,我看到了您所做的更改,这是有意义的。然而,我并不真正理解代码部分…@HristoGeorgiev我想我知道这个问题,但是为了验证它,你能把你文件的内容添加到你的问题中吗?问题是,此函数假设您输入的字符串格式完全相同,即3个用空格分隔的单词。您不理解哪些代码部分?我可以试着简化它们或者更好地解释它们。文件的内容是关于玩家的。例如:切尔西右后卫大卫·扎帕科斯塔2000万
def tuple_to_string(person_tuple):
    """Converts a tuple with person data into a string. This is is inverse function to `string_to_tuple`.

    person_tuple must be in the following format: (first_name, last_name, salary)
    A string of the following format is returned: "first_name last_name salary"

    e.g.
    >>> string_person = "John Miller 100"
    >>> string_person_2 = tuple_to_string(string_to_tuple(string_person))
    >>> string_person == string_person_2
    True
    >>> tuple_to_string(('John', 'Miller', 100))
    'John Miller 100'
    """
    string_person = " ".join(str(i) for i in person_tuple)
    return string_person

path_to_file = "my_file.txt"
with open(path_to_file, "r") as file:
    content = file.read() # alternatives: file.readlines() or file.readline()

print(content) # To ensure the content was correctly read. Not needed in the later application
>>> type(path_to_file)
<class 'str'>
>>> type(file)
<class '_io.TextIOWrapper'>
with open(path_to_file, "r") as file:
    for line in file.readlines():
        tuple_person = string_to_tuple(line)
        print(tuple_person) # verify output