Python – Read & Write .Text

READ DATA

content.txt

Paragraph 1
Paragraph 2
Paragraph 3
Paragraph 4
Paragraph 5

app.py

Example 1 :

# open file
file = open("content.txt", "r")

# read file
content = file.read()

# print
print(content)

# close file
file.close()

Result :
Paragraph 1
Paragraph 2
Paragraph 3
Paragraph 4
Paragraph 5
Example 2 :

# open file
file = open("content.txt", "r")

# read file
content = file.readlines()

# print
print(content)


print(content[0])
print(content[1])

# close file
file.close()

Result :
['Paragraph 1\n', 'Paragraph 2\n', 'Paragraph 3\n', 'Paragraph 4\n', 'Paragraph 5']

Paragraph 1

Paragraph 2

WRITE DATA

app.py

Example 1 (Data String) : 

data = """Text 1
Text 2
Text 3
Text 4
Text 5
"""

file = open("content.txt", "w")

# write data
file.write(data)

# close file
file.close()
Example 2 (Data list) :

data = ["Text 1", "Text 2", "Text 3"]

file = open("content.txt", "w")

# write data
for d in data:
    text = "{}\n".format(d)
    file.write(text)


# close file
file.close()
Example 3 (Data Dictionary) :

data = {
  "no": "1",
  "title": "Title 1",
  "desc": "Desc 1"
}

file = open("content.txt", "w")

# write data
text = "No = {}\nTitle = {}\nDesc = {}\n".format(data['no'], data['title'], data['desc'])
file.write(text)

# close file
file.close()
Example 4 (Data List of Dictionary/Json) :

data = [
    {
      "no": "1",
      "title": "Title 1",
      "desc": "Desc 1"
    },
    {
      "no": "2",
      "title": "Title 2",
      "desc": "Desc 2"
    },
    {
      "no": "3",
      "title": "Title 3",
      "desc": "Desc 3"
    }
]

file = open("content.txt", "w")

# write data
for d in data:
    text = "No = {}\nTitle = {}\nDesc = {}\n\n".format(d['no'], d['title'], d['desc'])
    file.write(text)

# close file
file.close()

Leave a Reply

Your email address will not be published. Required fields are marked *