简体   繁体   English

如何使用python用列表中的几个数字替换文本文件中的字符串?

[英]How to substitute string in a text file with a couple of numbers in a list using python?

The example is that there is a list lst=[2,4,6,8,10] and a text file which contains 'h = 1', I would like to change 1 into the numbers in lst, and keep the rest of that text remains the same, saving in separate text files automatically. 例如,有一个列表lst = [2,4,6,8,10]和一个包含“ h = 1”的文本文件,我想将1更改为lst中的数字,并保留其余部分该文本保持不变,自动保存在单独的文本文件中。 I wrote a dumb one using .replace('h=1','h=2').... But it won't work when it comes to a large amount since I have to edit it manually. 我使用.replace('h = 1','h = 2')....写了一个哑巴。但是,当涉及大量内容时,由于我必须手动对其进行编辑,因此它不起作用。 How could I realize the function given by a random input list, the text file could be substituted with the value in the list? 如何实现随机输入列表提供的功能,文本文件可以替换为列表中的值?

use str.format() . 使用str.format()。 {} is a wildcard in your string. {}是字符串中的通配符。 '{} is the number {}'.format('one', 1) returns the string 'one is the number 1' '{} is the number {}'.format('one', 1)返回字符串'one is the number 1'

file_name = 'the_file_{}.txt'
my_list = [2, 3, 4, 5, 6]
for num in my_list:
    new_file = open(file_name.format(num), 'w')
    new_text = big_text_string.replace('h=1', 'h={}'.format(num))
    new_file.write(new_text)
    new_file.close()

you could write a function that takes the list as a variable. 您可以编写一个将列表作为变量的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM