Home > database >  Convering a text file ( containing input like "A","B","C" ) to a neste
Convering a text file ( containing input like "A","B","C" ) to a neste

Time:09-06

Input File Contents:

"A.B.C.D","user","test123" "W.X.Y.Z","user","test123"

there can be multiple lines similar to the above in the input text file.

I am using below code :

filepath = "<path>/connect.txt"

def func(x):
    try:                                                         
        return int(x)
    except ValueError:
        return x
with open(filepath) as f:
    table_data = [[ func(x) for x in line.split()] for line in f]
    
print (table_data)

which seems to be doing its task, but creating problem as well.

Output:

[['"A.B.C.D","user","test123"'], ['"W.X.Y.Z","user","test123"']]

Is there a way I can remove single quote (') in above output.

Expected output:

[["A.B.C.D","user","test123"], ["W.X.Y.Z","user","test123"]]

CodePudding user response:

Input file:

"A.B.C.D","user","test123"
"W.X.Y.Z","user","test123"

Code:

import csv
filepath = "connect.txt"

def func(x):
    try:                                                         
        return int(x)
    except ValueError:
        return x
with open(filepath) as f:
    table_data = list(csv.reader([line for line in f]))

print(table_data)

Result:

[
    ['A.B.C.D', 'user', 'test123'],
    ['W.X.Y.Z', 'user', 'test123']
]

CodePudding user response:

Just add split(',') to convert the string to list, and replace("\"", "") to remove the extra " characters from the elements.

filepath = "<path>/connect.txt"

def func(x):
    try:                                                         
        return int(x)
    except ValueError:
        return x
with open(filepath) as f:
    table_data = [[ func(x).replace("\"", "") for x in line.split(',')] for line in f]
    
print (table_data)

The output:

[['A.B.C.D', 'user', 'test123'], ['W.X.Y.Z', 'user', 'test123']]
  • Related