file_name = input("Enter the file name: ") #magicsquares.txt
#show users the table
infile = open(file_name, "r")
file = infile.readlines()
infile.close()
#converting the numbers in notepad into a list (integers)
table= []
for i in range (len(file)):
row= file[i].split(' ')
for j in range (len(row)):
row[j]= int(row[j])
table.append(row)
print (row)
#selecting cells
select1 = int(input("Enter row number: "))
select2= int(input("Enter column number: "))
这是一个魔术方块,其中列表位于记事本文本文件中。如何选择列表中的行和列,以便我可以更改列表中特定坐标的值?
例如,用户输入坐标[0] [1]。如何在记事本文件中找到该坐标并提示用户输入一个整数来替换坐标[0] [1]处的原始值?
答案 0 :(得分:1)
我们假设您的输入文件sample.txt
包含以空格' '
分隔的数字列表,其中包含以下内容:
1 2 3 4
5 6 7 8
9 0 1 2
1 4 7 9
以上是类似矩阵的结构。
python代码看起来像这样:
import fileinput
import linecache
file_name = input("Enter the file name: ") #sample.txt
# selecting cells
select1 = int(input("Enter row number: ")) #0
select2 = int(input("Enter column number: ")) #1
# New value
newVal = int(input("Enter row number: ")) #100
# Get nth line from the input file and strip any newline chars
textToSearch = linecache.getline(file_name, select1+1).strip('\n')
# Transform to the line read to a list
tmpList = [int(_) for _ in textToSearch.split(' ')]
# Replace the list with the new value and form the str line back again
tmpList[select2] = newVal
textToReplace = ' '.join(str(_) for _ in tmpList)
# Modify the sample.txt file inplace
with fileinput.FileInput(file_name, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(textToSearch, textToReplace), end='')
file.close()
linecache.clearcache()
sample.txt
现在看起来像这样:
1 100 3 4
5 6 7 8
9 0 1 2
1 4 7 9
注意:这是Python3特有的
重要资源: