How to write to a file in an organized manner?

守給你的承諾、 提交于 2019-12-13 03:15:19

问题


I have this code:

file = open('scores.txt','w')
playerscores = []
playernames = [['A'],['B'],['C'],['D'],['E'],['F']]   
for y in range(6):
    for z in range(5):
            print("Enter score from Judge",z+1,"for couple ",playernames[0+y],"in round 1:")
            playerscores.append(int(input()))    
MY_LIST = str(playerscores)
for_every = 4

Essentially, I want to write to the file by making the the following index positions print on a new line

playerscore[0:6]
playerscore[7:13]

etc

So it would look like:

1,1,1,1,1,1,1,1,1,1

and not [1,1,1,1,1,1]

I need to do this so when i do

file = open('filename','r')

and call a position, it is easily given out.


回答1:


Here's some code that does what you want, although it gets its data from my get_data() function instead of from input(). This makes the code easier to test. But you can easily replace the get_data() call with input() once you've finished developing the program.

The key idea is that as well as saving the integer version of the input data to playerscores we also save it in its original string form in a separate list named row. So when we've finished reading the data for a given row we can easily save it to the file. This is simpler than trying to split the data up from playerscores and converting it back into strings.

from random import seed, randrange

# Seed the randomizer
seed(42)

# Make some fake data, to simulate user input.
# Print & return a random number from 1 to 5, in string form
def get_data():
    n = str(randrange(1, 6))
    print(n)
    return n

playernames = ['A', 'B', 'C', 'D', 'E', 'F']

numjudges = 5

playerscores = []
scoresfile = open('scores.txt', 'w')

for players in playernames:
    row = []
    for z in range(1, numjudges + 1):
        print("Enter score from Judge", z, "for couple ", players, "in round 1:")
        data = get_data()
        playerscores.append(int(data))
        row.append(data)
    scoresfile.write(','.join(row) + '\n')
    print()
scoresfile.close()

typical output

Enter score from Judge 1 for couple  A in round 1:
1
Enter score from Judge 2 for couple  A in round 1:
1
Enter score from Judge 3 for couple  A in round 1:
3
Enter score from Judge 4 for couple  A in round 1:
2
Enter score from Judge 5 for couple  A in round 1:
2

Enter score from Judge 1 for couple  B in round 1:
2
Enter score from Judge 2 for couple  B in round 1:
1
Enter score from Judge 3 for couple  B in round 1:
5
Enter score from Judge 4 for couple  B in round 1:
1
Enter score from Judge 5 for couple  B in round 1:
5

Enter score from Judge 1 for couple  C in round 1:
4
Enter score from Judge 2 for couple  C in round 1:
1
Enter score from Judge 3 for couple  C in round 1:
1
Enter score from Judge 4 for couple  C in round 1:
1
Enter score from Judge 5 for couple  C in round 1:
2

Enter score from Judge 1 for couple  D in round 1:
2
Enter score from Judge 2 for couple  D in round 1:
5
Enter score from Judge 3 for couple  D in round 1:
5
Enter score from Judge 4 for couple  D in round 1:
1
Enter score from Judge 5 for couple  D in round 1:
5

Enter score from Judge 1 for couple  E in round 1:
2
Enter score from Judge 2 for couple  E in round 1:
5
Enter score from Judge 3 for couple  E in round 1:
4
Enter score from Judge 4 for couple  E in round 1:
2
Enter score from Judge 5 for couple  E in round 1:
4

Enter score from Judge 1 for couple  F in round 1:
5
Enter score from Judge 2 for couple  F in round 1:
3
Enter score from Judge 3 for couple  F in round 1:
1
Enter score from Judge 4 for couple  F in round 1:
2
Enter score from Judge 5 for couple  F in round 1:
4

contents of scores.txt

1,1,3,2,2
2,1,5,1,5
4,1,1,1,2
2,5,5,1,5
2,5,4,2,4
5,3,1,2,4



回答2:


If I understood correctly you are looking for something like this:

l = [4,3,2,5,6,4,6]
# split l in chunks -> e.g. [[4,3,2], [5,6,4,6]] 
chunks = [[4,3,2], [5,6,4,6]]

with open('file.txt', 'w') as f: 
    for i,chunk in enumerate(chunks):
        if i!=0:
            f.write('\n'+','.join(str(i) for i in chunk))
        else:
            f.write(','.join(str(i) for i in chunk))

# read data back in ls as integers
ls = []
with open('file.txt', 'r') as f:
    lines = f.read().splitlines()
    for line in lines:
        ls += map(int,line.split(','))

print ls


来源:https://stackoverflow.com/questions/46570575/how-to-write-to-a-file-in-an-organized-manner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!