Satyam Shishodiya
Satyam Shishodiya

Reputation: 11

how to add double quotes to a string in text file

I have a file with words that are each in a separate line. I want to read each word and add quotes around it, and a comma after the word. After that I want the words back into a new text file with the added symbols.

Example, this as input file:

ram 
shyam
raja

I want this to be in the output file:

"ram",
"shyam",
"raja"

Upvotes: 0

Views: 1674

Answers (2)

bvdl
bvdl

Reputation: 421

If each word is on the same line of the input file, separated by spaces. Then you could approach it like this:

# read lines from file
text = ""
with open('filename.txt', 'r') as ifile:
    text = ifile.readline()

# get all sepearte string split by space
data = text.split(" ")

# add quotes to each one
data = [f"\"{name}\"" for name in data]

# append them together with commas inbetween
updated_text = ", ".join(data)

# write to some file
with open("outfilename.txt", 'w') as ofile:
    ofile.write(updated_text)

Input:

jeff adam bezos

Output

"jeff", "adam", "bezos"

If you want to work with each input and output file word on a separate line, we could take this approach:

# read lines from file
words = []
with open('filename.txt', 'r') as ifile:
    words = [line.replace("\n", "") for line in ifile.readlines()]

# add quotes to each one
updated_words = [f"\"{word}\"" for word in words]

# append them together with commas inbetween
updated_text = ",\n".join(updated_words)

# write to some file
with open("outfilename.txt", 'w') as ofile:
    ofile.write(updated_text)

Input:

jeff
adam
bezos

Output

"jeff",
"adam",
"bezos"

Good Luck!

Upvotes: 2

Arifa Chan
Arifa Chan

Reputation: 1015

Read the file as list using read().splitlines() and write the line using f-string and writelines:

with open('text.txt', 'r') as r: lines = r.read().splitlines()
with open('text.txt', 'w') as w: w.writelines(f'"{line}",'+'\n' for line in lines)

Upvotes: 1

Related Questions