1

I'm writing some code in Python to read from a file some text, and make a 2-dimensional array from it. But when I make the array, in the last spot of the first 2 array(of three) there is : '\n', and I want delete it.

This is the file(data.txt):

a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z

And this is the Python code:

data = open("data.txt", mode="r")

arr = data.readlines()

for i in range(len(arr)):
    arr[i] = list(arr[i].split(","))

#here I tryed to detele it
for i in range(len(arr)):
    if arr[i][len(arr[i])-1] == '\\n':
       del arr[len(arr[i])-1]

data.close()

This is the result of the code(but there is anyway '\n'):

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\n']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\n']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

How I could delete those?

2
  • the \n is a newline character to indicate a line break in the file you're reading. you can use the list.pop or .remove functions, or you can simply do like arr[i] = arr[i][:-1]. Commented Aug 6, 2017 at 15:54
  • 1
    These are "\n", not "\\n" Commented Aug 6, 2017 at 15:54

4 Answers 4

3

Short solution using str.rstrip() and str.splitlines() functions:

with open('data.txt', 'r') as f:
    items = [l.rstrip(',').split(',') for l in f.read().splitlines()]
    print(items)

The output:

[['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']]
Sign up to request clarification or add additional context in comments.

Comments

2

You can use rstrip and list comprehension.

with open("data.txt", 'r', encoding="utf-8") as file:
    array = [line.rstrip(',\n').split(',') for line in file]

Comments

0

You can filter the list and only keep values that are not "\n":

for i in range(len(arr)):
     arr[i] = [b for b in arr[i] if b != "\n"]

Comments

0

You can just strip the \n as you read the lines:

arr = []

with open('data.txt', mode="r") as f:
    for line in f.readlines():
        arr.append(line.strip(',\n').split(','))

print arr

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.