定义函数参数和列表迭代

问题描述 投票:0回答:1

我对 Python 非常陌生,但有 javascript 经验。下面是我的程序的一部分,由于“remove_comment_lines”中的参数“data”未定义,因此未运行。我如何定义数据并将其用作指定函数的参数而不使用“全局”,因为我的教授不允许这样做。

读取文件并返回字符串格式的行列表

def read_data(data):
    with open("in.dat", "r") as f:
        data = f.readlines()
    f.close()
    return data

read_data("in.dat")


# Takes a list of lines as input and returns a new list of lines with the 
# comment lines (the ones that begin with #) removed.
def remove_comment_lines(data):
    with open("in.dat", "w") as f1:
        for number, data in enumerate(data):
            if number not in [0,1,2]:
                f1.write(data)
    f1.close()

remove_comment_lines(data)

这是文件“in.dat”

# read from file data about one day 
# format: start_time:end_time:#steps
09.30AM:09.45AM:220
11.45AM:12.23PM:300
11.45AM:10.23AM:302
2.45PM:3.23PM:202
3.45PM:3.53PM:90
5.45PM:5.53PM:80
6.45PM:7.23PM:1000
10.45PM:10.53PM:102

我已经尝试了所有我能想到的方法。我期望函数打开文件“indat”并删除以“#”开头的行并返回由行分隔的列表。

python function arguments iteration
1个回答
0
投票

with
上下文管理器不需要您使用
f.close()

您可以使用
if line.startswith('#'): continue
移动到循环/文件的下一个迭代,而不是写入该行。
https://onlinegdb.com/Fr3wQYvoD

def read_data(data):
    with open("in.dat", "r") as f:
        data = f.readlines()
    return data

# Takes a list of lines as input and returns a new list of lines with the 
# comment lines (the ones that begin with #) removed.
def remove_comment_lines(data):
    with open("in.dat", "w") as f:
        for line in data:
            if line.startswith('#'): continue
            f.write(line)

# read file as list of lines and save to variable
data = read_data("in.dat")

# pass data to remove comment function
remove_comment_lines(data)
© www.soinside.com 2019 - 2024. All rights reserved.