读取文件并将文件中的数据提供给函数

时间:2018-12-08 03:46:12

标签: python

因此,基本上我需要编写一些代码来提示用户输入文件名并尝试打开提供的任何名称。然后,程序应从文件中读取每一行,并将其提供给我创建的函数,然后函数将文件中的文本转换为元组。

到目前为止,我拥有该文件: https://i.gyazo.com/76db0e6bd91b0c457c40e4b1b692afd7.png

,此为函数: https://i.gyazo.com/32e431a1ed638fb3072fe19e0c31d551.png

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助:

from os.path import isfile, exists

filename = input('Enter file name : ')

if(exists(filename) and isfile(filename)):     
    with open(filename) as f:
        content = f.readlines()
    # Call your function here with content as argument and process it, content has all lines in the file as a list

答案 1 :(得分:0)

我不太确定您共享的第二个功能链接是否适合这里。但是您想要做的一个通用解决方案是:

filepath = input("Message")

with open(filepath) as fp:  
   line = fp.readline()
   while line:
       line = fp.readline()
       custom_function(line) #Define and call your function

希望有帮助。