Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否有python函数来替换文本文件中特定列表中的特定索引?_Python - Fatal编程技术网

是否有python函数来替换文本文件中特定列表中的特定索引?

是否有python函数来替换文本文件中特定列表中的特定索引?,python,Python,我想做的是: 我现在在一个文本文件中有几个列表,我只想使用python更改其中一个列表中的一个元素。 到目前为止我所做的: 当前txt文件: food,bought oranges,yes strawberry,no apples,no 在使用代码将其中一个“否”替换为“是”后,我希望它显示如下: 有没有办法专门更改列表中的一个索引?如果文件足够小,可以放入内存,只需读取、替换并重写即可 idx = 3 with open(file_name, 'r') as f: file = f.

我想做的是: 我现在在一个文本文件中有几个列表,我只想使用python更改其中一个列表中的一个元素。 到目前为止我所做的:

当前txt文件:

food,bought
oranges,yes
strawberry,no
apples,no
在使用代码将其中一个“否”替换为“是”后,我希望它显示如下:


有没有办法专门更改列表中的一个索引?

如果文件足够小,可以放入内存,只需读取、替换并重写即可

idx = 3
with open(file_name, 'r') as f:
    file = f.readlines()

line = file[idx].split(',')
line[1] = 'yes'
file[idx] = ','.join(line)

with open(file_name, 'w') as f:
    for line in file:
        f.write(line)
这对我很有用:

def change_file(index):
with open("test.txt", 'r+') as file:
    lines = file.readlines()
    for i, line in enumerate(lines):
        if i == index:
            lines[i] = line.replace('no', 'yes')
    file.seek(0)
    file.writelines(lines)

change_file(3)

您可以通过使用
Dataframe
加载文件并根据需要使用来更改任何索引的值

例如:

将熊猫作为pd导入
data=pd.read_csv(“filename.txt”,sep=“,”)
打印(数据)
>>> 
购买的食物
0个橙子是的
1号草莓
2个苹果没有
现在要更改一些索引,有多种方法

  • 特定索引:
    索引
    可以是int或list
    index=2
    data.loc[索引,“购买”]=“是”
    >>> 
    购买的食物
    0个橙子是的
    1号草莓
    2个苹果是的
    
  • 带值筛选:如果知道要更改哪些值,请使用以下条件筛选这些值并添加替换值
  • data.loc[data[“food”]=“apples”,“bunded”]=“yes”
    >>>
    购买的食物
    0个橙子是的
    1号草莓
    2个苹果是的
    
    您能澄清一下您想做什么吗?文件没有索引,但列表很容易更改。是否要更改从文件读取的列表,还是要更改文件本身?欢迎使用StackOverflow,和在这里申请。这能回答你的问题吗?你能解释一下你的答案吗?什么不清楚?我从txt文件中获取所有内容作为列表。
    data[-1]
    是我们的
    data.txt
    的最后一行,我将“否”替换为所需的“是”。现在可以理解了吗?
    def change_file(index):
    with open("test.txt", 'r+') as file:
        lines = file.readlines()
        for i, line in enumerate(lines):
            if i == index:
                lines[i] = line.replace('no', 'yes')
        file.seek(0)
        file.writelines(lines)
    
    change_file(3)
    
    with open('data.txt', 'r') as f:
        data = f.readlines()
    with open('data.txt', 'w') as f:
        data[-1] = data[-1].replace("no", "yes")
        f.writelines(data)