I have data in text file as
- ram
- shyam
- raja
I want to update it into
- "ram",
- "shyam",
- "raja"
ignore the 1.,2.,3. these are only used for formatting.
CodePudding user response:
Here you go:
# 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 = [ "\"" 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)
Good Luck!
CodePudding user response:
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)