【问题标题】:Python reading and writing to a .txt filePython 读取和写入 .txt 文件
【发布时间】:2017-03-17 14:08:26
【问题描述】:

我需要从 babynames2014.txt 文件中读取名字,然后创建两个新文件,将男孩和女孩的名字分开。生成的文件应称为boynames2014.txt 和girlnames.txt。 babynames2014.txt 文件如下所示:

1 诺亚·艾玛

2 利亚姆·奥利维亚

3 梅森·索菲亚

4 雅各布·伊莎贝拉

并继续直到达到 100 个男孩和女孩的名字。 到目前为止,我编写的代码创建了两个新的文本文件,但 boynames2014 不包含任何内容,而 girlnames2014 仅包含名称 Noah 和前面的数字 1,如下所示:1Noah。

我认为我需要使用readline()line.split() 在某个地方,我只是不确定在哪里以及如何正确使用它们。如果找不到 babynames2014.txt 文件,我还需要使用 try/except 块来处理异常。

    infile = open("babynames2014.txt", "r")    
    outfile = open("boynames2014.txt", "w")
    outfile = open("girlnames2014.txt", "w")


    line = infile.readline()
    datafield = line.split()
    boyname2014 = datafield[0]
    girlname2014 = datafield[1]
    outfile.write(boyname2014)
    outfile.write(girlname2014)


    infile.close()
    outfile.close()

我只学习了 2-3 个月的 Python,非常感谢任何可以帮助我了解更多信息的建议!

【问题讨论】:

  • 好吧,您没有得到您期望的结果的原因很少,我们可以提供帮助!给一个babynames2014.txt的样例。编辑:我刚刚注意到你有一个样本。

标签: python


【解决方案1】:

我注意到一件事在逻辑上是不正确的,即 outfile 同时适用于 boynames2014.txt 和 girlnames2014.txt

你应该这样做的。

infile = open("babynames2014.txt", "r")    
outfile_boys = open("boynames2014.txt", "w")
outfile_girls = open("girlnames2014.txt", "w")

然后,您必须读取 infile 并按新行拆分所需数据,如下所示。

lines = infile.read().split("\n")

然后遍历下面的行并按空格分隔(默认)。

for line in lines:
    datafield = line.split()
    boyname2014 = datafield[1]
    girlname2014 = datafield[2]
    outfile_boys.write(boyname2014 + '\n')
    outfile_girls.write(girlname2014 + '\n')

我为数据字段选择了 1 和 2 索引,因为您的文件包含如下数据:

1 boy_name girl_name

按空间分割将 boy_name 传递到第一个索引girl_name 到第二个索引

然后照常关闭文件。

infile.close()
outfile_boys.close()
outfile_girls.close()

希望对你有帮助!

【讨论】:

  • 非常感谢!非常感谢您解释了所有内容,这确实有助于我更好地理解!
  • 乐于帮助@Andrew N.
【解决方案2】:

您需要为输出文件提供单独的指针。

`
infile = open("babynames2014.txt", "r")
outfileboy = open("boynames2014.txt", "w")
outfilegirl = open("girlnames2014.txt", "w")
for line in infile.readlines():
    names = line.split(" ")
    outfileboy.write(str(names[1]+"\n")
    outfilegirl.write(str(names[2]+"\n")

outfileboy.close()
outfilegirl.close()

`

【讨论】:

    【解决方案3】:
        outfile1 = open("boynames2014.txt", "w")
        outfile2 = open("girlnames2014.txt", "w")
        with open('babynames2014.txt') as infile:
            for line in infile:
                datafield = line.split()
                boyname2014 = datafield[0]
                girlname2014 = datafield[1]
                outfile1.write(boyname2014)
                outfile2.write(girlname2014)
        outfile1.close()
        outfile2.close()
    

    【讨论】:

      【解决方案4】:

      readline() 只读取一行(顾名思义) 所以只有第一行被读取(1 Noah Emma)

      要读取所有行并将它们拆分并将它们写入文件尝试:

      # use two different names for the files
      # you had one name `outfile` which was being 
      # overwritten so tht why boy file was empty
      
      infile = open("babynames2014.txt", "r") 
      boyfile = open("boynames2014.txt", "w") 
      girlfile = open("girlnames2014.txt", "w")
      
      with open('babynames2014', 'r') as f:
          for l in f.readlines(): # notice readlines instead of readline
              _, boy, girl = l.split() # assumes the separator is a space
              print(boy, file=boyfile)
              print(girl, file=girlfile)
      
      # don't forget to close your file desciptors
      boyfile.close()
      girlfile.close()
      

      【讨论】:

        【解决方案5】:

        给你,

        #! /usr/bin/python
        import sys
        
        boy_file = str(sys.argv[1])
        girl_file = str(sys.argv[2])
        
        all_records = [line.strip() for line in open('babynames2014', 'r')]
        
        f1 = open(boy_file, "w")
        f2 = open(girl_file, "w")
        
        for record in all_records:
                split_record = record.split(' ')
                boy_name = split_record[1]
                girl_name = split_record[2]
        
                f1.write(boy_name+"\n")
                f2.write(girl_name+"\n")
        
        
        f1.close()
        f2.close()
        

        【讨论】:

          【解决方案6】:

          您为两个输出文件指定了相同的变量名。 outfile.

              infile = open("babynames2014.txt", "r")    
              outfileb = open("boynames2014.txt", "w")
              outfileg = open("girlnames2014.txt", "w")
          
          
              line = infile.readline()
              datafield = line.split()
              boyname2014 = datafield[0]
              girlname2014 = datafield[1]
              outfileb.write(boyname2014)
              outfileg.write(girlname2014)
          
          
              infile.close()
              outfileb.close()
              outfileg.close()
          

          并且您需要遍历输入文件以获取所有名称。 您可以使用''.join([i for i in s if not i.isdigit()]) 删除名称中的数字。

              infile = open("babynames2014.txt", "r")    
              outfileb = open("boynames2014.txt", "w")
              outfileg = open("girlnames2014.txt", "w")
          
          
              tmp = infile.readline()
              line=''.join([i for i in tmp if not i.isdigit()])
              datafield = line.split()
              boyname2014 = datafield[0]
              girlname2014 = datafield[1]
              outfileb.write(boyname2014)
              outfileg.write(girlname2014)
          
          
              infile.close()
              outfileb.close()
              outfileg.close()
          

          【讨论】:

          • 您的代码仍然不正确,因为您对两个文件都使用了outfile
          【解决方案7】:

          想要考虑正则表达式解决方案吗?

          with open("babynames2014.txt", "r") as f1,open("boynames2014.txt", "w") as boys,open("girlnames2014.txt","w") as girls:
              # Note this will not work for name which has speacial charecters like `-,$,etc`
              boy_regex = re.compile(r"^\d\s?([a-zA-z0-9]+)\s[a-zA-z0-9]+$",re.MULTILINE)
              girl_regex = re.compile(r"^\d\s?[a-zA-z0-9]+\s([a-zA-z0-9]+)$",re.MULTILINE)
              boys.write('\n'.join(boy_regex.findall(f1.read())))
              girls.write('\n'.join(girl_regex.findall(f1.read())))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-05-29
            • 1970-01-01
            • 2021-07-15
            • 2013-03-25
            • 2013-02-02
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多