Seán Dempsey
Seán Dempsey

Reputation: 105

Read from text file to a string?

I am reading the values from a text file to a string. When al the values are read into the string i need to put them into quotes and be separated by a comma.

An example of this would be in the text file i would have:

123456789
123456789
123456789
123456789

and I read it into my string data_to_read and I would like it to show:

data_to_read = "1234567892","1234567892","1234567892","1234567892"

I can read it into the string but cannot figure out how to add the quotes and commas.

with open('C:\uiautomation\Test_Files\Securities_to_Delete.txt', 'r') as input:
    data_to_read = "".join(input.readlines()[1:])
    print data_to_read

This outputs:

'123456789\n123456789\n123456789\n123456789'

Upvotes: 0

Views: 97

Answers (2)

Nick-H
Nick-H

Reputation: 388

This works also for python versions that support f-strings:

new_str = ','.join([f'"{item}"' for item in data_to_read.split()])

Upvotes: 1

Moira Jones
Moira Jones

Reputation: 369

You can use the replace string method to do this:

'"' + data_to_read.replace("\n", '","') + '"'

Upvotes: 1

Related Questions