将特定字符串添加到文件中特定行的末尾

2024-04-24 10:25:57 发布

您现在位置:Python中文网/ 问答频道 /正文

所以现在我有:

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) 

Tags: 文件toaddstringaswithsomeopen
2条回答

^{}^{}^{}是您需要的工具:

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])

您可以对任何大小的文件执行以下操作:

    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))

相关问题 更多 >