【问题标题】:read and write from and to file using functions使用函数读取和写入文件
【发布时间】:2020-10-01 14:33:52
【问题描述】:

我正在尝试创建 2 个函数。

  1. readfiles(file_path),读取由 file_path 指定的文件,并返回包含文件中每一行的字符串列表。

  2. writefiles(lines, file_path) 将列表行的内容逐行写入 file_path 指定的文件。

当一个接一个使用时,输出文件应该是输入文件的精确副本(包括格式)

这是我目前所拥有的。

file_path = ("/myfolder/text.txt", "r")
def readfiles(file_path):
    with open file_path as f:
        for line in f:
            return line
            lst = list[]
            lst = line
            lst.append(line)
            return lst
read_file(file_path)

lines = lst []
def writefiles(lines, file_path):
    with open ("file_path", "w") as f: 
    for line in lst:
        f.write(line)
        f.write("\n")

当我用它来阅读时,我可以让它发挥作用

with open("/myfolder/text.txt", "r") as f:
    for line in f:
        print(line, end='')

这个是写

with open ("/myfolder/text.txt", "w") as f: 
    for line in f:
        f.write(line)
        f.write("\n")

但是当我尝试将它们放入函数时,一切都搞砸了。 我不知道为什么,我知道这是一个简单的问题,但它只是不适合我。我已经阅读了有关它的文档,但我没有完全遵循它并且我束手无策。我的功能有什么问题?

我收到不同的错误

 lst = list[]
               ^
SyntaxError: invalid syntax

lst or list is not callable 

我也知道有类似的问题,但我发现的问题似乎没有定义函数。

【问题讨论】:

    标签: python-3.x list function


    【解决方案1】:

    你的代码的问题解释为 cmets

    file_path = ("/myfolder/text.txt", "r") # this is a tupple of 2 elements should be file_path = "/myfolder/text.txt"
    def readfiles(file_path):
        with open file_path as f: # "open" is a function and will probably throw an error if you use it without parenthesis
        # use open this way: open(file_path, "r")
            for line in f:
                return line # it will return the first line and exit the function
                lst = list[] # "lst = []" is how you define a list in python. also you want to define it outside the loop
                lst = line # you are replacing the list lst with the string in line
                lst.append(line) # will throw an error because lst is a string now and doesn't have the append method
                return lst
    read_file(file_path) # should be lines = read_file(file_path)
    
    lines = lst [] # lines is an empty list 
    def writefiles(lines, file_path):
        with open ("file_path", "w") as f: 
        for line in lst: # this line should have 1 more tabulation
            f.write(line) # this line should have 1 more tabulation
            f.write("\n") # this line should have 1 more tabulation
    

    代码如下所示

    def readfiles(file_path):
        lst = []
        with open(file_path) as f:
            for line in f:
                lst.append(line.strip("\n"))
        return lst
    
    
    def writefiles(lines, file_path):
        with open(file_path, "w") as f:
            for line in lines:
                f.write(line + "\n")
    
    
    file_path = "/myfolder/text.txt"
    filepathout = "myfolder/text2.txt"
    lines = readfiles(file_path)
    writefiles(lines, filepathout)
    

    一种更 Pythonic 的方式

    # readlines is a built-in function in python
    with open(file_path) as f:
        lines = f.readlines()
    
    # stripping line returns
    lines = [line.strip("\n") for line in lines]
    
    # join will convert the list to a string by adding a \n between the list elements
    with open(filepathout, "w") as f:
        f.write("\n".join(lines))
    

    关键点:

    - the function stops after reaching the return statement
    
    - be careful where you define your variable. 
      i.e "lst" in a for loop will get redefined after each iteration
    

    定义变量:

    - for a list: list_var = []
    
    - for a tuple: tup_var = (1, 2)
    
    - for an int: int_var = 3
    
    - for a dictionary: dict_var = {}
    
    - for a string: string_var = "test"
    

    【讨论】:

    • 谢谢,我设法从 Airsquids 的回答中弄清楚了,但这非常有帮助。
    【解决方案2】:

    这里有几个学习点会有所帮助。

    在你的阅读功能中,你有点接近。但是,您不能将return 语句放入循环中。一旦函数第一次到达任何地方,它就会结束。此外,如果您要创建一个容器来保存读取的内容列表,则需要在开始循环之前创建它。最后,不要命名任何东西list。它是一个关键字。如果您想创建一个新列表项,只需执行以下操作:results = list()results = []

    所以在伪代码中,你应该:

    Make a list to hold results
    Open the file as you are now
    Make a loop to loop through lines
        append to the results list
    return the results (outside the loop)
    

    您的writefiles 非常接近。您应该循环访问作为函数参数的 lines 变量。现在你引用lst 这不是你的函数的参数。

    祝你好运!

    【讨论】:

    • 谢谢你的帮助,我明白了:)
    猜你喜欢
    • 2018-01-08
    • 2015-07-26
    • 2019-01-24
    • 2010-11-11
    • 1970-01-01
    • 2023-04-07
    • 2012-03-15
    • 2019-04-25
    • 1970-01-01
    相关资源
    最近更新 更多