[英]Python: How can I read in the characters from a line in a file and convert them to floats and strs, depending on if they are numbers or letters?
[英]I have 3 lines in a `.txt` file each line containing 3 numbers and I want to `+1` to them numbers depending on the user input
所以基本上我有一个包含 3 行的文件,每行有 3 个数字
7,2,1
10,0,0
2,8,0
然后根据用户输入,我想对该行中的一个数字 +1。
if user_input == 1
+1 to line1Number1
elif user_input == 2
+1 to line1Number2
elif user_input == 3
+1 to line1Number3
else
print"error"
你可以这样做:
In [1634]: user_input = int(input())
In [1627]: with open('t.txt', 'r') as f:
...: lines = f.readlines()
...: for c,l in enumerate(lines):
...: if c == user_input:
...: lst = l.split(',')
...: lst = [int(x) + 1 for x in lst]
...: print(lst)
[3, 9, 1]
with open(filename, "r") as txtr:
data = txtr.readlines()
data = [x.split(",") for x in data]
for i in range(len(data)):
for j in range(len(data[i])):
data[i][j] = int(data[i][j])
data 现在有 3 个列表,每个列表有 3 个数字。
if user_input == 1
data[0] = [x+1 for x in data[0]]
只需对 rest 执行相同操作即可。
保存到文本文件:
ndata = [",".join(x) for x in data]
nndata = "\n".join(ndata)
with open(filename, "w") as txtw:
txtw.write(nndata)
另一种方法(评论中的解释)。 从 in.txt 读取,写入 out.txt。
# ask user input for which column to update
update_column = int(input("Column to update 1,2 or 3?"))
# open file to read from
with open("in.txt", "r") as f:
# for every line in the text file
for line in f.readlines():
# make the numbers into an integer list (remove new line, split by comma, and convert to int)
new_line = list(map(int, line.strip().split(",")))
# add one to the number in the column input
new_line[update_column -1] +=1
# open a file for a pending
with open("out.txt", "a") as of:
# append the list removing brackets and adding a new line
of.write(str(new_line).replace("[","").replace("]","") + "\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.