【问题标题】:How can I read certain characters from a .txt file and write them to a .csv file in Python?如何从 .t​​xt 文件中读取某些字符并将它们写入 Python 中的 .csv 文件?
【发布时间】:2020-10-01 08:44:19
【问题描述】:

所以我目前正在尝试使用 Python 从 .txt 文件创建一个整洁的 .csv 文件。第一阶段是将一些 8 位数字放入一个称为“数字”的列中。我已经创建了标题,只需将每行中的每个数字放入列中。我想知道的是,如何告诉 Python 读取 .txt 文件中每行的前八个字符(对应于我要查找的数字),然后将它们写入 .csv 文件?这可能很简单,但我只是 Python 新手!

到目前为止,我有一些看起来像这样的东西:

with open(r'C:/Users/test1.txt') as rf:
    with open(r'C:/Users/test2.csv','w',newline='') as wf:
        outputDictWriter = csv.DictWriter(wf,['Number'])
        outputDictWriter.writeheader()
        writeLine = rf.read(8)
        for line in rf:
            wf.write(writeLine)

【问题讨论】:

    标签: python csv write


    【解决方案1】:

    你可以使用pandas:

    import pandas as pd
    
    df = pd.read_csv(r'C:/Users/test2.txt')
    df.to_csv(r'C:/Users/test2.csv')
    

    以下是如何读取文件中每行的前 8 个字符并将它们存储在列表中:

    with open('file.txt','r') as f:
        lines = [line[:8] for line in f.readlines()]
    

    【讨论】:

    • 非常感谢您的建议 :) 我尝试使用 Pandas,虽然它的组织方式比以前好一些,但它仍然不是我想要的。本质上,我希望它看起来像这样:Numbers Name 12345678 nameOfPerson 24681012 nameOfPerson2 36912151 nameOfPerson3 To: Numbers 12345678 24681012 36912151
    • 对不起,格式很奇怪......但本质上,我只想写一列,从不是数字的行中删除信息
    • @PSwa916 我添加了它。
    【解决方案2】:

    您可以使用正则表达式来选择带有字符的数字。搜索它 模式 = re.searh(w*\d{8})

    【讨论】:

      【解决方案3】:

      只需退后一步,再次阅读您需要的内容:

      读取 .txt 文件中每行的前八个字符(对应于我要查找的数字),然后将它们写入 .csv 文件

      现在忘记 Python 并用伪代码解释要做什么:

      open txt file for reading
      open csv file for writing (beware end of line is expected to be \r\n for a CSV file)
      write the header to the csv file
      loop reading the txt file 1 line at a time until end of file
          extract 8 first characters from  the line
          write them to the csv file, ended with a \r\n
      close both files
      

      好的,是时候将上面的伪代码转换为 Python 语言了:

      with open('C:/Users/test1.txt') as rf, open('C:/Users/test2.csv', 'w', newline='\r\n') as wf:
          print('Number', file=wf)
          for line in rf:
              print(line.rstrip()[:8], file=wf)
      

      【讨论】:

      • 这行得通,正是我所需要的!太棒了,非常感谢:D
      猜你喜欢
      • 1970-01-01
      • 2015-06-26
      • 2014-07-25
      • 2021-01-11
      • 2014-03-17
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多