【问题标题】:Python - Read text and write into csv. Replace empty columns as a default 'N/A' valuePython - 读取文本并写入 csv。将空列替换为默认的“N/A”值
【发布时间】:2021-12-01 02:18:14
【问题描述】:

我有一个 txt 文件,“iteration.txt”。 我只想抓取“部分”之后的数据以写入 csv。
“A 部分”有 2 个输入和输出。 “B 部分”没有输入和输出,我想将“N/A”放在空列中。

'iteration.txt'

Input-> 000
Output-> 000
Codex153 @ Section_A_Iterating
Input-> 101
Output-> 010
unwanted data
Input-> 320
Output-> 321
unwanted data
Codex173 @ Section_B_Extracting
Codex183 @ Section_C_Iterating
unwanted data
unwanted data
Input->011
Output-> 011

我已经完成的代码:

with open('iteration.csv', 'w') as writer:
    flag = False
    writer.write ('Section,Input,Output'+'\n')
    for eachline in open('iteration.txt').readlines():

        if 'Section' in eachline:
            flag = True
            writer.write (eachline.split()[-1]+'\n')
            #print (section_list)

        if flag:
            if 'Input' in eachline:
                writer.write (eachline.strip() + '\n')

            if 'Output' in eachline:
                writer.write(eachline.strip() + '\n')

上述代码的CSV输出:

预期的 csv 数据:

对不起,我是新手,我不太确定如何将“N/A”放在空列中,以及如何根据其各自的标题放置数据。有什么简单的方法可以做到这一点,最好不要过多地更改上面的代码? 谢谢!

【问题讨论】:

    标签: python csv text


    【解决方案1】:

    使用函数.fillna('N/A') ,您可以填充空值或不存在的值。

    【讨论】:

    • OP 没有使用 pandas。
    • 感谢您的评论。我明白了,嗯……有没有办法不使用 pandas 来做到这一点?
    • 这可能有效。在正则表达式的帮助下替换空字符串 wirh "N/A"。 stackoverflow.com/questions/16720541/…
    • yourstring.replace("", "N/A") 应该可以工作
    猜你喜欢
    • 2021-04-28
    • 2020-01-30
    • 2012-10-01
    • 2017-09-11
    • 2022-08-03
    • 2016-09-29
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多