【问题标题】:Writing into a specific location in a text file写入文本文件中的特定位置
【发布时间】:2022-11-30 03:03:40
【问题描述】:

如何将字符串/整数添加到特定位置的现有文本文件中?
我的示例文本如下所示:

No, Color, Height, age
1, blue,70,
2, white,65,
3, brown,49,
4, purple,71,
5, grey,60,

我的文本文件有 4 列,三列有文本,我如何写入第四列中的任何一行?
如果我想将 12 写入第二行,更新后的文件 (sample.txt) 应该如下所示:

No, Color, Height, age
1, blue,70,12
2, white,65,
3, brown,49,
4, purple,71,
5, grey,60,

我试过这个:

with open("sample.txt",'r') as file:
    data =file.readlines()
data[1]. split(",") [3] = 1
with open ('sample.txt', 'w') as file:
  file.writelines(data)
with open ('sample.txt', 'r') as file:
    print (file. Read())

但它不起作用。需要你的帮助。

【问题讨论】:

  • 您在拆分后编辑了该行,但未对原始行进行任何更改。在执行拆分和变异后尝试data[1] = split_data_1.join(',') 或类似的。

标签: python text overwrite file-writing


【解决方案1】:

另一种方法是将该文本文件读入列表并根据索引追加,如下所示。

with open('sample.txt') as file:
    lines = [line.rstrip() for line in file]

line1 = lines[1]
new_line1 = line1 + str(12)
lines[1] = new_line1

with open('sample.txt', mode='wt', encoding='utf-8') as f:
    f.write('
'.join(lines))

更新了 sample.txt

No, Color, Height, age
1, blue,70,12
2, white,65,
3, brown,49,
4, purple,71,
5, grey,60,

解释:

阅读要列出的文本文件后。

0th element will ebcome  ---> index(1st line)
1st element will become ----> 2nd line 
---
--

--

基于索引访问并使用 + 运算符附加字符串

【讨论】:

    【解决方案2】:

    在这个例子中,我使用了一个二维数组,它对我很有效。尝试一下,如果它不起作用或者您需要更深入的解释,请发送聊天消息给我。

    with open("sample.txt", 'r') as file:
      data = file.readlines()
    
      for index, item in enumerate(data):
        data[index] = item.strip("
    ")
    
      for index, item in enumerate(data):
        data[index] = item.split(", ")
    
    data[1][3] = "12"
    
    ndata = []
    
    for index, _ in enumerate(data):
      data1 = ", ".join(data[index])
      ndata.append(data1)
    
    mdata = "
    ".join(ndata)
    
    with open("sample.txt", 'w') as file:
      file.write(mdata)
    

    【讨论】:

      猜你喜欢
      • 2017-11-09
      • 1970-01-01
      • 2013-10-18
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 2020-04-07
      相关资源
      最近更新 更多