【问题标题】:Changing every line of a text file in python在python中更改文本文件的每一行
【发布时间】:2019-04-12 09:37:31
【问题描述】:

我有一个包含 50,000 行的文件。所有行的形式为:

A,B

A,B

A,B

等等…… 我想编辑该文件(或者甚至更好,创建一个新文件),这样最后我的文本文件将如下所示:

一个

一个

一个

...

基本上擦除 , 和 B。 我怎样才能以最有效的方式做到这一点?

   # Create a new file for the new lines to be appended to

   f = open("file.txt", "r")
      for line in f:
          # Take the A,B form and send only the A to a new file

谢谢

【问题讨论】:

  • 好吧,对于初学者来说,如果您以'w' 模式打开,您将无法遍历f...此外,它会截断您的文件,因此您将丢失你的数据...所以不要那样做...
  • 我不介意丢失我的数据,因为我有一个副本,我还不如创建一个新文件,对我来说没关系。
  • 对,但重点是您将无法以这种方式读取数据。通常,您只需打开两个文件,您正在读取的文件(以 'r' 模式打开),然后写入一个新文件(以 'w' 模式单独打开)
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 On topichow to ask... the perfect question 在此处申请。 StackOverflow 不是设计、编码、研究或教程资源。但是,如果您遵循您在网上找到的任何资源,进行诚实的编码尝试并遇到问题,那么您将有一个很好的示例可以发布。
  • 特别是,这个问题可能由系统实用程序更好地处理,例如 UNIX (Linux) 上的 awksed

标签: python file append


【解决方案1】:

又快又脏的python脚本,但是……

# Open the file as read
f = open("text.txt", "r+")
# Create an array to hold write data
new_file = []
# Loop the file line by line
for line in f:
  # Split A,B on , and use first position [0], aka A, then add to the new array
  only_a = line.split(",")
  # Add
  new_file.append(only_a[0])
# Open the file as Write, loop the new array and write with a newline
with open("text.txt", "w+") as f:
  for i in new_file:
    f.write(i+"\n")

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 2014-12-21
    • 2020-07-06
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多