如何更改代码在我的文件中写入数据的方式

时间:2015-03-14 16:26:32

标签: python layout

当我运行代码时,它会在.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()

3 个答案:

答案 0 :(得分:1)

在您的代码中

     scoresFile.write( "%s,%s\n" % (record["name"],(record["scores"])) ) 


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 = []
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()

答案 1 :(得分:1)

首先,您在record["scores"]

中的数据
['["[\'2\']"', " '3']", '10']
  • list
    • ["[\'2\']" - string
    • '3'] - string
    • 10 - string

并非所有字符都是纯数字(您有'["等字符。

需要对待,我的猜测是问题在于您将新项目添加到record["scores"]列表。


我们假设我们只有record["scores"]

中的数字

e.g。

 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

答案 2 :(得分:1)

使用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

>>>