将数据转换为cs时将其写入文本文件

2024-06-06 20:16:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python很陌生。我有一个.txt文件,想把它转换成一个.csv文件的格式,我被告知,但无法完成。一只手是有用的。我要用截图来解释。你知道吗

我有一个txt文件名为bip.txt文件. 里面的数据是like this

我想把它转换成csv,比如this csv file

到目前为止,我所能做的只是用以下代码从文本文件中写入所有数据:

read_files = glob.glob("C:/Users/Emrehana1/Desktop/bip.txt")

with open("C:/Users/Emrehana1/Desktop/Test_Result_Report.csv", "w") as outfile:
    for f in read_files:
        with open(f, "r") as infile:
            outfile.write(infile.read())

那么,有没有一个解决方案,以转换成一个csv文件的格式,我的愿望?我希望我已经解释清楚了。你知道吗


Tags: 文件csv数据txtread格式withfiles
2条回答

不使用glob函数打开文件,而是搜索与模式匹配的文件名。你可以打开文件bip.txt文件然后读取每一行并将值放入一个数组中,然后在找到所有值后,用新行和逗号连接它们并写入csv文件,如下所示:

# set the csv column headers
values = [["test", "outcome"]]

current_row = []
with open("bip.txt", "r") as f:
    for line in f:
        # when a blank line is found, append the row
        if line == "\n" and current_row != []:
            values.append(current_row)
            current_row = []

        if ":" in line:
            # get the value after the semicolon
            value = line[line.index(":")+1:].strip()
            current_row.append(value)
    # append the final row to the list
    values.append(current_row)


# join the columns with a comma and the rows with a new line
csv_result = ""
for row in values:
    csv_result += ",".join(row) + "\n"

# output the csv data to a file
with open("Test_Result_Report.csv", "w") as f:
    f.write(csv_result)

如果您只有一个文件并且已经知道它的名称,那么就不需要使用glob模块。你可以打开它。以文本形式引用数据会很有帮助,因为作为图像,想要帮助您的人不能只复制和粘贴您的输入数据。你知道吗

对于输入文件中的每个条目,您必须读取多行以收集在输出文件中创建条目所需的信息。你知道吗

一种方法是循环输入行,直到找到一个以“test:”开头的行,然后使用next()在文件中获取下一行来创建条目:

下面的代码将生成所需的分割-创建csv文件可以使用标准库模块完成,并留作练习。我使用了不同的文件名,如您所见。你知道吗

with open("/tmp/blip.txt") as f:
    for line in f:
        if line.startswith("test:"):
            test_name = line.strip().split(None, 1)[1]
            result = next(f)
            if not result.startswith("outcome:"):
                raise ValueError("Test name not followed by outcome for test "+test_name)
            outcome = result.strip().split(None, 1)[1]
            print test_name, outcome

相关问题 更多 >