【问题标题】:Add specific string to the end of specific lines from files将特定字符串添加到文件中特定行的末尾
【发布时间】:2017-02-04 23:09:54
【问题描述】:

所以现在我有:

1,A
2,B
3,C

如何使用python写入文件并制作:

1,A,some_string1
2,B,some_string2
3,C,some_string3

我发现的只是一个解决方案,可以像这样将相同的字符串添加到每一行:

1,A,abc
2,B,abc
3,C,abc

使用:

file_name = "thing"
string_to_add = "abc"

with open('thing', 'r') as f:
    file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in   f.readlines()]

with open('thing', 'w') as f:
    f.writelines(file_lines) 

【问题讨论】:

  • 随机字符串应该有一定的长度吗?
  • 不,它们可以是任何东西

标签: python csv add lines


【解决方案1】:

你可以对任何大小的文件这样做:

    import random

    with open('input.csv') as in_file:
        with open('out.csv', 'w') as out_file:
            for in_line in in_file:
                in_line = in_line.strip()
                rand_line = random.randint(1,100)  # your random string
                out_file.write("{},{}\n".format(in_line, rand_line))

【讨论】:

  • 你能解释一下为什么你打开两个不同的文件吗?
  • 原地修改文件没有简单的解决办法。
【解决方案2】:

csvstringrandom 是您正在寻找的工具:

import csv
import string
import random

with open('input.csv') as fin:
  with open('output.csv', 'w') as fout:
    writer = csv.writer(fout)
    for row in csv.reader(fin):
      # random string of length 6 consisting of any upper/lower case ascii letters
      rand_str = ''.join(random.choice(string.lowercase) for x in range(6))
      writer.writerow(row + [rand_str])

【讨论】:

  • 抱歉没有正确解释,当我说 random_string 时,我的意思是我制作的字符串不是通过 random 模块生成的。
猜你喜欢
  • 1970-01-01
  • 2017-03-04
  • 2022-06-11
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多