简体   繁体   中英

I'm trying to write random numbers to a file and then make a list from lines in Python but list takes '\n' too

I'm using a function to create random numbers and writing them line by line in a file named random.txt using \\n in a for loop using this block of code:

dosya.write(str(randomNumber))
dosya.write('\n')

I need to make a list from lines and then sort that list using a sort function. I can see my random numbers line by line in that file but when I use readline() function like:

List = open("random.txt").readlines()
print List

the output is:

['22\n', '16\n', '1\n',  '4\n', '4\n']

why am I seeing \\n after my numbers? I tried printing only first or second element and it didn't show any extra thing. What is wrong with whole list? When I use sort function it takes \\n as well.

Loop through each line and cast the line to an int and append to an array.

f=open('random.txt','r')

array = []
for line in f: # read  lines
    array.append(int(line))

f.closed

The .readlines() methods reads each line including the line ending \\n as a list element. You likely want your random numbers as integers anyway. Converting them to int would make your sorting work also:

with open("random.txt") as fobj:
    data = [int(line) for line in fobj]

The with opens the file with the promise to close it as soon as you leave the indentation. The open file object fobj is iterable. Therefore, you can write a list comprehension directly over fobj converting each line into an integer. It removes all newline characters n automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM