如何更改代码在我的文件中写入数据的方式
how to change how the code writes the data in my file
当我 运行 代码时,它在 .txt 文件中留下的数据如下所示:
s,['["[\'2\']"', " '3']", '10']
我需要它看起来像这样:
s,2,3,10
这是我的代码:
pname = input("What is your name")
correct = input("What is your score")
SCORE_FILENAME = "Class1.txt"
MAX_SCORES = 3
try: scoresFile = open('Class1.txt', "r+")
except IOError: scoresFile = open('Class1.txt', "w+") # File not exists
actualScoresTable = []
for line in scoresFile:
tmp = line.strip().replace("\n","").split(",")
for index, score in enumerate(tmp[1:]):
tmp[1+index] = str(score)
actualScoresTable.append({
"name": tmp[0],
"scores": tmp[1:],
})
scoresFile.close()
new = True
for index, record in enumerate( actualScoresTable ):
if record["name"] == pname:
actualScoresTable[index]["scores"].append(correct)
if len(record["scores"]) > MAX_SCORES:
actualScoresTable[index]["scores"].pop(0) # OR del actualScoresTable[index]["scores"][0]
new = False
break
if new:
actualScoresTable.append({
"name": pname,
"scores": [correct],
})
scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for record in actualScoresTable:
for index, score in enumerate(record["scores"]):
record["scores"][index] = str(score)
scoresFile.write( "%s,%s\n" % (record["name"],(record["scores"])) )
scoresFile.close()
在你的代码中
scoresFile.write( "%s,%s\n" % (record["name"],(record["scores"])) )
scoresFile.close()
你有列表记录["scores"]被发送到字符串,记住,你需要值记录["scores"][索引]记录。
pname = input("What is your name")
correct = input("What is your score")
SCORE_FILENAME = "Class1.txt"
MAX_SCORES = 3
try: scoresFile = open('Class1.txt', "r+")
except IOError: scoresFile = open('Class1.txt', "w+") # File not exists
actualScoresTable = []
for line in scoresFile:
tmp = line.strip().replace("\n","").split(",")
for index, score in enumerate(tmp[1:]):
tmp[1+index] = str(score)
actualScoresTable.append({
"name": tmp[0],
"scores": tmp[1:],
})
scoresFile.close()
new = True
for index, record in enumerate( actualScoresTable ):
if record["name"] == pname:
actualScoresTable[index]["scores"].append(correct)
if len(record["scores"]) > MAX_SCORES:
actualScoresTable[index]["scores"].pop(0) # OR del actualScoresTable[index]["scores"][0]
new = False
break
if new:
actualScoresTable.append({
"name": pname,
"scores": [correct],
})
scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for record in actualScoresTable:
for index, score in enumerate(record["scores"]):
record["scores"][index] = str(score)
scoresFile.write( "%s,%s\n" % (record["name"],(record["scores"][index])) )
scoresFile.close()
这里有一些代码可以执行您想要执行的操作。
pname = input("What is your name")
correct = input("What is your score")
SCORE_FILENAME = "Class1.txt"
MAX_SCORES = 3
try: scoresFile = open('Class1.txt', "r+")
except IOError: scoresFile = open('Class1.txt', "w+") # File not exists
actualScoresTable = dict()
for line in scoresFile:
tmp = line.replace("\n","").split(",")
actualScoresTable[tmp[0]]=tmp[1:]
scoresFile.close()
if pname not in actualScoresTable.keys():
actualScoresTable[pname] = [correct]
else:
actualScoresTable[pname].append(correct)
if MAX_SCORES < len(actualScoresTable[pname]):
actualScoresTable[key].pop(0)
scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for key in actualScoresTable.keys():
scoresFile.write("%s,%s\n" % (key, ','.join(actualScoresTable[key])))
scoresFile.close()
首先,你的数据在record["scores"]
['["[\'2\']"', " '3']", '10']
list
["[\'2\']"
- 字符串
'3']
- 字符串
10
- 字符串
并非所有字符都是纯数字(您有像 </code>、<code>'
、[
、"
这样的字符)。
这需要处理,我的猜测是问题出在您将新项目添加到 record["scores"]
列表的地方。
假设 record["scores"]
中只有数字
例如
record["name"] = 's'
record["scores"] = ['2', '3', '10']
现在这应该可以按您的要求工作了
items = list()
items.append(record["name"])
items.extend(record["scores"]) # which is list, so it should work
scoresFile.write(','.join(items) + '\n')
会输出
s,2,3,10
编辑:添加示例
SCORE_FILENAME = 'scores.txt'
# -------------------------------
# TODO: inputs to construct `actualScoresTable`
actualScoresTable = [
{ "name": "Millan", "scores": ['1', '2', '3']},
{ "name": "Obama", "scores": ['55', '11', '32']},
]
# -------------------------------
# This is how you should output it to a file as you requested
with open(SCORE_FILENAME, "w+") as scoresFile:
for record in actualScoresTable:
items = list()
items.append(record["name"])
items.extend(record["scores"])
scoresFile.write(','.join(items) + '\n')
会输出成scores.txt
下面的
Millan,1,2,3
Obama,55,11,32
使用 str.join
将列表项连接成一个字符串:
>>> a = ['4', '10']
>>> ','.join(a)
'4,10'
>>> ' | '.join(a)
'4 | 10'
>>> ' * '.join(a)
'4 * 10'
>>>
假设 actualScoresTable
看起来像这样:
actualScoresTable = [{'scores': ['4', '10'], 'name': 'f'},
{'scores': ['8', '3'], 'name': 'g'}]
以所需格式写入文件,如下所示:
# a couple of helpers for code readability
import operator
name = operator.itemgetter('name')
scores = operator.itemgetter('scores')
with open('outfile.txt', 'w') as f:
for record in actualScoresTable:
line = '{},{}\n'.format(name(record), ','.join(scores(record)))
print(line)
f.write(line)
>>>
f,4,10
g,8,3
>>>
当我 运行 代码时,它在 .txt 文件中留下的数据如下所示:
s,['["[\'2\']"', " '3']", '10']
我需要它看起来像这样:
s,2,3,10
这是我的代码:
pname = input("What is your name")
correct = input("What is your score")
SCORE_FILENAME = "Class1.txt"
MAX_SCORES = 3
try: scoresFile = open('Class1.txt', "r+")
except IOError: scoresFile = open('Class1.txt', "w+") # File not exists
actualScoresTable = []
for line in scoresFile:
tmp = line.strip().replace("\n","").split(",")
for index, score in enumerate(tmp[1:]):
tmp[1+index] = str(score)
actualScoresTable.append({
"name": tmp[0],
"scores": tmp[1:],
})
scoresFile.close()
new = True
for index, record in enumerate( actualScoresTable ):
if record["name"] == pname:
actualScoresTable[index]["scores"].append(correct)
if len(record["scores"]) > MAX_SCORES:
actualScoresTable[index]["scores"].pop(0) # OR del actualScoresTable[index]["scores"][0]
new = False
break
if new:
actualScoresTable.append({
"name": pname,
"scores": [correct],
})
scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for record in actualScoresTable:
for index, score in enumerate(record["scores"]):
record["scores"][index] = str(score)
scoresFile.write( "%s,%s\n" % (record["name"],(record["scores"])) )
scoresFile.close()
在你的代码中
scoresFile.write( "%s,%s\n" % (record["name"],(record["scores"])) )
scoresFile.close()
你有列表记录["scores"]被发送到字符串,记住,你需要值记录["scores"][索引]记录。
pname = input("What is your name")
correct = input("What is your score")
SCORE_FILENAME = "Class1.txt"
MAX_SCORES = 3
try: scoresFile = open('Class1.txt', "r+")
except IOError: scoresFile = open('Class1.txt', "w+") # File not exists
actualScoresTable = []
for line in scoresFile:
tmp = line.strip().replace("\n","").split(",")
for index, score in enumerate(tmp[1:]):
tmp[1+index] = str(score)
actualScoresTable.append({
"name": tmp[0],
"scores": tmp[1:],
})
scoresFile.close()
new = True
for index, record in enumerate( actualScoresTable ):
if record["name"] == pname:
actualScoresTable[index]["scores"].append(correct)
if len(record["scores"]) > MAX_SCORES:
actualScoresTable[index]["scores"].pop(0) # OR del actualScoresTable[index]["scores"][0]
new = False
break
if new:
actualScoresTable.append({
"name": pname,
"scores": [correct],
})
scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for record in actualScoresTable:
for index, score in enumerate(record["scores"]):
record["scores"][index] = str(score)
scoresFile.write( "%s,%s\n" % (record["name"],(record["scores"][index])) )
scoresFile.close()
这里有一些代码可以执行您想要执行的操作。
pname = input("What is your name")
correct = input("What is your score")
SCORE_FILENAME = "Class1.txt"
MAX_SCORES = 3
try: scoresFile = open('Class1.txt', "r+")
except IOError: scoresFile = open('Class1.txt', "w+") # File not exists
actualScoresTable = dict()
for line in scoresFile:
tmp = line.replace("\n","").split(",")
actualScoresTable[tmp[0]]=tmp[1:]
scoresFile.close()
if pname not in actualScoresTable.keys():
actualScoresTable[pname] = [correct]
else:
actualScoresTable[pname].append(correct)
if MAX_SCORES < len(actualScoresTable[pname]):
actualScoresTable[key].pop(0)
scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for key in actualScoresTable.keys():
scoresFile.write("%s,%s\n" % (key, ','.join(actualScoresTable[key])))
scoresFile.close()
首先,你的数据在record["scores"]
['["[\'2\']"', " '3']", '10']
list
["[\'2\']"
- 字符串'3']
- 字符串10
- 字符串
并非所有字符都是纯数字(您有像 </code>、<code>'
、[
、"
这样的字符)。
这需要处理,我的猜测是问题出在您将新项目添加到 record["scores"]
列表的地方。
假设 record["scores"]
中只有数字
例如
record["name"] = 's'
record["scores"] = ['2', '3', '10']
现在这应该可以按您的要求工作了
items = list()
items.append(record["name"])
items.extend(record["scores"]) # which is list, so it should work
scoresFile.write(','.join(items) + '\n')
会输出
s,2,3,10
编辑:添加示例
SCORE_FILENAME = 'scores.txt'
# -------------------------------
# TODO: inputs to construct `actualScoresTable`
actualScoresTable = [
{ "name": "Millan", "scores": ['1', '2', '3']},
{ "name": "Obama", "scores": ['55', '11', '32']},
]
# -------------------------------
# This is how you should output it to a file as you requested
with open(SCORE_FILENAME, "w+") as scoresFile:
for record in actualScoresTable:
items = list()
items.append(record["name"])
items.extend(record["scores"])
scoresFile.write(','.join(items) + '\n')
会输出成scores.txt
下面的
Millan,1,2,3
Obama,55,11,32
使用 str.join
将列表项连接成一个字符串:
>>> a = ['4', '10']
>>> ','.join(a)
'4,10'
>>> ' | '.join(a)
'4 | 10'
>>> ' * '.join(a)
'4 * 10'
>>>
假设 actualScoresTable
看起来像这样:
actualScoresTable = [{'scores': ['4', '10'], 'name': 'f'},
{'scores': ['8', '3'], 'name': 'g'}]
以所需格式写入文件,如下所示:
# a couple of helpers for code readability
import operator
name = operator.itemgetter('name')
scores = operator.itemgetter('scores')
with open('outfile.txt', 'w') as f:
for record in actualScoresTable:
line = '{},{}\n'.format(name(record), ','.join(scores(record)))
print(line)
f.write(line)
>>>
f,4,10
g,8,3
>>>