If \n is added when creating a new file after reading the Python file readline

Asked 1 years ago, Updated 1 years ago, 137 views

Code to create a new file called test.csv by reading a file called test.csv.

Delete the other parts and upload only the problematic parts. As a result, I solved it in a different way, but I have a question because I don't understand something.

The records in the original file have no spaces when written as follows, but in the new file, all records are followed by \n and the length of the record is longer than the original value.

I wrote the code to count the values separately, but I wonder which part of the code below gives \n.

file='C:/test.csv'
with open('C:/test.csv','w',newline='') as testfile:
    csv_writer=csv.writer(testfile)
    with open (file,'r') as infile:
        for line in infile:
            lst=[line]
            csv_writer.writerow(lst)

python readline

2022-09-22 20:01

2 Answers

The intention of the questioner is that where did the invisible /n appear, and should it be counted except for /n?

However, as Jung Young-hoon said above, the line feed (/n) was not visible, and it basically exists, and it is normal to count when you count the number of words.

An example is as follows:

#test.csv content is a. It's b. It's c. 
#One line at a time.
with open('C:/Users/CEO/Desktop/test.csv','r') as testfile:    
    for line in testfile :
        a=line
        print(len(a),type(a),a)


#The results are as follows.
>> 6 <class 'str'> a.
>> 6 <class 'str'> b.
>> 6 <class 'str'> c.

It's a. If you solve it, it looks like a, mouth, ni, da, and so on. But the reason why len is 6 is because /n is also counted.

If you still don't know,

 print(a[0])
 print(a[1])
 print(a[2])
 print(a[3])
 print(a[4])
 print(a[5])

You can see that /n exists as a value.


2022-09-22 20:01

Of course, you have to have a line feed.

What's csv is just a text file.

a,a,a,a
b,b,b,b

If there is no \n in the

a,a,a,ab,b,b,b

It's going to be it.

It's not the result you want.


2022-09-22 20:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.