【问题标题】:Edit last element of each line of text file编辑每行文本文件的最后一个元素
【发布时间】:2019-12-05 12:01:26
【问题描述】:

我有一个包含一些元素的文本文件;

0,The Hitchhiker's Guide to Python,Kenneth Reitz,2/4/2012,0
1,Harry Potter,JK Rowling,1/1/2010,8137
2,The Great Gatsby,F. Scott Fitzgerald,1/2/2010,0
3,To Kill a Mockingbird,Harper Lee,1/3/2010,1828

这些列表的最后一个元素决定了哪个用户取出了给定的书。如果为 0,则没有人拥有它。 我想要一个代码来将任何给定行的 ',0' 替换为输入的 4 位数字,以显示有人拿出了这本书。

我已使用 .replace 将其从 1828 年更改为例如到 0 但是我不知道如何将特定行的最后一个元素从 0 更改为其他元素。

由于工作/教育限制,我无法使用 csv,因此我必须将文件保留为 .txt 格式。

我也只能使用标准 python 库,因此没有 pandas。

【问题讨论】:

  • 这是csv 模块的工作。
  • 您的数据是 CSV 格式的,因此您应该首先将其加载为 CSV 格式(使用 csv.readerpandas.read_csv)。这将返回一个易于使用的数据结构。进行更改,然后将其写回 CSV(csv.writerpandas.to_csv)。
  • 应该添加到我的问题中:我不能使用 csv,它必须是 .txt 格式。
  • 您仍然可以使用 csv 模块将其加载为 .txt 文件。
  • 这是我不知道的。我将对 csv 进行一些研究,看看我在哪里。感谢您的帮助!

标签: python python-3.x list csv


【解决方案1】:

您可以使用read_csvtxt 捕获到数据帧中:

import pandas as pd


df = pd.read_csv("text_file.txt", header=None)
df.columns = ["Serial", "Book", "Author", "Date", "Issued"]
print(df)
df.loc[3, "Issued"] = 0
print(df)
df.to_csv('text_file.txt', header=None, index=None, sep=',', mode='w+')

这会将第三本书的发行计数替换为 0。

Serial                              Book               Author      Date  \
0       0  The Hitchhiker's Guide to Python        Kenneth Reitz  2/4/2012   
1       1                      Harry Potter           JK Rowling  1/1/2010   
2       2                  The Great Gatsby  F. Scott Fitzgerald  1/2/2010   
3       3             To Kill a Mockingbird           Harper Lee  1/3/2010   

   Issued  
0       0  
1    8137  
2       0  
3    1828  

   Serial                              Book               Author      Date  \
0       0  The Hitchhiker's Guide to Python        Kenneth Reitz  2/4/2012   
1       1                      Harry Potter           JK Rowling  1/1/2010   
2       2                  The Great Gatsby  F. Scott Fitzgerald  1/2/2010   
3       3             To Kill a Mockingbird           Harper Lee  1/3/2010   

   Issued  
0       0  
1    8137  
2       0  
3       0  

评论后编辑: 如果你只需要使用 python 标准库,你可以通过文件读取来做这样的事情:

import fileinput

i = 0
a = 5 # line to change with 1 being the first line in the file
b = '8371'
to_write = []

with open("text_file.txt", "r") as file:
    for line in file:
        i += 1
        if (i == a):
            print('line before')
            print(line)
            line = line[:line.rfind(',')] + ',' + b + '\n'
            to_write.append(line)
            print('line after edit')
            print(line)
        else:
            to_write.append(line)
print(to_write)

with open("text_file.txt", "w") as f: 
    for line in to_write:
            f.write(line)

文件内容

0,The Hitchhiker's Guide to Python,Kenneth Reitz,2/4/2012,0
1,Harry Potter,JK Rowling,1/1/2010,8137
2,The Great Gatsby,F. Scott Fitzgerald,1/2/2010,84
3,To Kill a Mockingbird,Harper Lee,1/3/2010,7895
4,XYZ,Harper,1/3/2018,258
5,PQR,Lee,1/3/2019,16

将此作为输出

line before
4,XYZ,Harper,1/3/2018,258

line after edit
4,XYZ,Harper,1/3/2018,8371

["0,The Hitchhiker's Guide to Python,Kenneth Reitz,2/4/2012,0\n", '1,Harry Potter,JK Rowling,1/1/2010,8137\n', '2,The Great Gatsby,F. Scott Fitzgerald,1/2/2010,84\n', '3,To Kill a Mockingbird,Harper Lee,1/3/2010,7895\n', '4,XYZ,Harper,1/3/2018,8371\n', '5,PQR,Lee,1/3/2019,16\n', '\n']

【讨论】:

  • 这看起来可以满足我的需求,但是一旦更改完成,我该如何将其重写回 txt 文件?
  • 不幸的是,我只能使用标准的 python 库,所以 pandas 不会是一个选项。令人沮丧。
  • 请看我更新的答案,这能解决你的问题吗?
  • 这似乎并没有改变任何东西,也许我做错了什么。我将输入“a”作为要更改的行,输入“b”作为更改值。例如 a=5 和 b=8371。
  • 它对我有用。确保您的文件至少有 5 行,并且 b 应该是一个字符串。请再次查看我的代码,我根据您的更改了我的变量。
【解决方案2】:

你可以试试这个:

to_write = []
with open('read.txt') as f:  #read input file
    for line in f:
        if int(line[-2]) ==0:
            to_write.append(line.replace(line[-2],'1234'))  #any 4 digit number
        else:
            to_write.append(line)


with open('output.txt', 'w') as f:  #name of output file
    for _list in to_write:

            f.write(_list)

【讨论】:

    猜你喜欢
    • 2014-10-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2015-01-28
    • 2016-05-09
    • 1970-01-01
    相关资源
    最近更新 更多