上面提供的几个解决方案都不错。这是一个更具描述性的方法:
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
您绝对应该花时间根据其他答案和阅读文档来改进这一点。