【问题标题】:File Manipulation in Python [duplicate]Python中的文件操作[重复]
【发布时间】:2015-12-09 04:23:16
【问题描述】:

所以我有一个作为文本文件的数据库,看起来像:

Panasonic VCR 943,1998/06/30,IN,Shelf 4
Canon Camera SLR,2010/07/02,OUT,Dr. James Jones
Apple iPad,2012/01/19,IN,Shelf 19

在单独的程序中打开该文件后,如何操作该文件中的内容,例如根据用户选择的行将第一行的 IN 更改为 Out 并将 Shelf 4 更改为 Mr.Smith?我需要这样做吗:

   for i in enumerate("file"):
      i == input("line want to change")

【问题讨论】:

标签: python python-3.x


【解决方案1】:

上面提供的几个解决方案都不错。这是一个更具描述性的方法:

import fileinput
import sys

filename = 'test.txt'

# ----
# print the line user asked for
def printline(linenumber):
    handle = open(filename)
    for i, line in enumerate(handle):
        if (i+1) == int(linenumber):
            print (line)
            # find a keyword to type here to exit for loop as soon as the line of interest is printed
    handle.close()

# ----

# ask user for the line number
linenumber = input('Please enter line number: ')
print ('Line %s is: ' % linenumber)
printline(linenumber)

# ask if IN/OUT has to be changed
answer = input('Switch IN to OUT --OR-- OUT to IN? (y/n): ');
if answer == 'y':

    # use fileinput to change the file in place
    for line in fileinput.input(filename, inplace = True):

        # if it is the line of interest, switch IN to OUT if ,IN, is found
        # switch OUT to IN if ,OUT, is found
        if fileinput.filelineno() == int(linenumber):
            if ',IN,' in line:
                print ('%s' % line.strip().replace(',IN,', ',OUT,'))
            else:
                print ('%s' % line.strip().replace(',OUT,', ',IN,'))

        # if this is not the right line, just print the line back to file
        else:
            print (line.strip())

    fileinput.close()

print ('Line %s is: ' % linenumber)
printline(linenumber)

print ('Done')

结果:

$ /c/Python34/python.exe test.py
Please enter line number: 2
Got it. Line 2 is:
Canon Camera SLR,2010/07/02,IN,Dr. James Jones

Switch IN to OUT --OR-- OUT to IN? (y/n): y
Line 2 is:
Canon Camera SLR,2010/07/02,OUT,Dr. James Jones

Done

您绝对应该花时间根据其他答案和阅读文档来改进这一点。

【讨论】:

    【解决方案2】:
    line = input("line want to change")
    with open('file.txt', 'r+') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
        for idx, row in enumerate(spamreader):
            if idx == line:
                do what you want
    
    Then rewrite the change to the file
    

    【讨论】:

    • csv 阅读器可能更适合访问特定列中的项目
    【解决方案3】:

    将文件转换成列表,即可享受Python带来的便利。完成处理后,列表可以再次保存为文件。

    with open("/Users/neo/test.txt", "rw") as file:
        file = [line.strip() for line in file]
        i = input("Enter the line #: ")
        print file[i]
    

    下面是用法

    > python ~/test.py
    Enter the line #: 2
    Apple iPad,2012/01/19,IN,Shelf 19
    

    【讨论】:

      猜你喜欢
      • 2021-06-22
      • 2020-07-06
      • 2014-06-25
      • 2019-09-04
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多