Python. Examples of working with text files




Examples of working with text files

This topic provides examples of writing and reading information for text files.


Contents


Search other websites:

1. Read/write list containing n integers

The following operations are shown in the example:

  • creating a list of 10 random numbers;
  • saving the list in a text file;
  • reading from a file to a new list for control purposes.

The text of the program is as follows:

# Writing/reading a list of random numbers
# 1. Connect the random module
import random

# 2. Create a list of 10 random numbers
i = 0
lst = []
while i<10:
    number = random.randint(0, 101) # number from 0 to 100
    lst = lst + [number]
    i = i+1

print("lst = ", lst)

# 3. Save the list in a text file
# 3.1. Save list to a text file
f = open('file.txt', 'wt')

# 3.2. Save the number of items in the list
s = str(len(lst)) # Convert integer to string
f.write(s + '\n') # Save the string

# 3.3. Save each item
for i in lst:
    s = str(i) # convert list item to string
    f.write(s + ' ') # write a number to a string

# 4. Close the file
f.close()

# -------------------------------------------
# 5. Reading from 'file.txt' file
f = open('file.txt', 'r')

# 6. Read numbers from the file and form a list
# 6.1. Read the number of items in the list,
#      a string is read first, then this string
#      is converted to an integer using the int() method
s = f.readline()
n = int(s)

# 6.2. Create an empty list
lst2 = []

# 6.3. Implement file traversal line by line and count numbers.
#     A file iterator is used to read lines.
for line in f:
    # split method - splits into words based on the space character
    strs = line.split(' ') # get an array of strs strings

    # Display strs for control purposes
    print("strs = ", strs)

    # read all words and write them down as integers
    for s in strs:
    if s!='':
        lst2 = lst2 + [int(s)] # add number to list

# 6.4. Display the result
print("n = ", len(lst2))
print("lst2 = ", lst2)

# 6.5. Close the file - optional
f.close()

The result of the program

lst = [48, 89, 1, 36, 68, 26, 61, 38, 1, 6]
strs = ['48', '89', '1', '36', '68', '26', '61', '38', '1', '6', '']
n = 10
lst2 = [48, 89, 1, 36, 68, 26, 61, 38, 1, 6]

 

2. Read/write list containing strings

When reading/writing lines, it is not necessary to implement additional conversions from one type to another, since the data from the file is read as lines.

 

# Writing/reading a list of strings
# 1. The specified list of strings
L = [ 'abc', 'bcd', 'cba', 'abd']

# 2. Open file for writing
f = open('filestrs.txt', 'wt')

# 3. Loop of write strings
for s in L:
    # write each line to a separate line in the file
    f.write(s + '\n')

# 4. Close the file
f.close()

# -------------------------------------------
# 5. Read from file 'filestrs.txt'
f = open('filestrs.txt', 'rt')

# 6. Form a new list
lst2 = [] # empty list

# 7. Implement file traversal line by line and count numbers.
#   A file iterator is used to read lines.
for s in f:
    # Remove the last character '\n' from s
    s = s.rstrip()

# Display s
print("s = ", s)

# Add string s to lst2 list
lst2 = lst2 + [s]

# 8. Display lst2 list
print("lst2 = ", lst2)

# 9. Close the file - not necessary
f.close()

The result of the program

s = abc
s = bcd
s = cba
s = abd
lst2 = ['abc', 'bcd', 'cba', 'abd']

 

3. Read/write tuple containing floating point objects

The example demonstrates writing and reading a tuple that contains floating point objects.

# Writing/reading a tuple containing objects of type float.
# 1. Source tuple
T1 = ( 3.8, 2.77, -11.23, 14.75)

# 2. Writing a tuple to a file
# 2.2. Open file for writing in text mode
f = open('myfile5.txt', 'wt')

# 2.3. The cycle of writing objects to a file
for item in T1:
    # 2.3.1. Convert the item to a string
    s = str(item)

    # 2.3.2. Write string + space character
    f.write(s + ' ')

    # 2.4. Close the file
    f.close()

# 3. Reading from a file that contains real numbers
#   and creating a new tuple T2
f = open('myfile5.txt', 'rt')

# 3.1. Create an empty tuple T2
T2 = ()

# 3.2. Reading data from a file and forming a tuple
for lines in f: # Use the file iterator
    # 3.2.1. Break the lines into strings.
    #       Any substring strings[i] is a real number,
    #       represented in string format
    strings = lines.split(' ')

# 3.2.2. Traverse all the substrings in the file,
#         convert and add them to the T2 tuple
for s in strings:
    if s != '': # if a non-empty string
    # Convert to the real number
    num = float(s)

# Add to the tuple
T2 += (num,)

# 3.3. Display the tuple
print("T2 = ", T2) # T2 =   (3.8, 2.77, -11.23, 14.75)

# 3.4. Close the file
f.close()

The result of the program

T2 = (3.8, 2.77, -11.23, 14.75)

View of myfile5.txt file

3.8 2.77 -11.23 14.75

 



4. Reading / writing a tuple containing objects of different types

If the tuple contains objects of different types during writing/reading, it is important follow to the sequence of stages of converting objects to the desired type. The following is an example of writing and reading a tuple that contains objects of integer, logical, and string types.

 

# Writing / reading a tuple containing objects of different types
# 1. Write tuple into the file

# 1.1. Given tuple
T1 = ( 5, True, "abcde fghi")

# 1.2. Open a file for writing in text mode
f = open('myfile4.txt', 'wt')

# 1.3. Writing a tuple to a file, since there are
#     lines in a tuple, we write each element
#     in a separate line
for item in T1:
    s = str(item) + '\n' # add newline
    f.write(s)

# Close the file
f.close()

# 2. Read the tuple
f = open('myfile4.txt', 'rt')

# 2.1. Create an empty tuple
T3 = ()

# 2.2. Reading data from a file and creating a tuple
#     The number of type int is read first
s = f.readline()
T3 = T3 + (int(s),) # concatenation

# The second reads a boolean value of type bool
s = f.readline()
T3 = T3 + (bool(s),)

# The third is a string of type str
s = f.readline()
s = s.rstrip() # remove the character '\n' from the string
T3 = T3 + (s,)

# 2.3. Display the tuple
print("T3 = ", T3) # T3 =   (5, True, 'abcde fghi')

# 2.4. Close the file
f.close()

The result of the program

T3 = (5, True, 'abcde fghi')

 

5. Read/Write Dictionary

The dictionary can also be written to a file. In this example, a dictionary is written and read that contains a list of weekday numbers and their names. To facilitate reading data, each element of the dictionary is placed on a separate string.

# Writing/reading a dictionary to a text file.
# The dictionary contains objects of type {int: str}

# 1. Source Dictionary - a list of days of the week and their numbers
D = { 1:'Sun', 2:'Mon', 3:'Tue', 4:'Wed', 5:'Thu', 6:'Fri', 7:'Sat' }

# 2. Write dictionary to file
# 2.1. Open text file for writing
f = open('myfile6.txt', 'w')

# 2.2. The cycle of writing dictionary elements to a file
for item in D:
    # 2.2.1. Generate a string of the form key:value
    s = str(item)     # get the key as a string
    s += ':'         # add symbol ':'
    s += D.get(item) # add value by it's key
    s += '\n'       # add new line symbol

    # 2.2.2. Write string to file
    f.write(s)

# 2.3. Close the file
f.close()

# 3. Reading from a file that contains dictionary data D
# 3.1. Open file for reading
f = open('myfile6.txt', 'rt')

# 3.2. Create an empty dictionary D2
D2 = {}

# 3.3. Reading data from a file and creating a new dictionary
for lines in f: # Use a file iterator
    # 3.3.1. Any substring of lines is an element of the form key:value
    #       represented in string format.
    #       Split lines into 2 substrings
    strings = lines.split(':')

    # 3.3.2. Get the key and value
    key = int(strings[0]) # get a key
    value = strings[1].rstrip() # get a value without '\n'

    # 3.3.3. Add key:value pair to D2 dictionary
    D2[key] = value

# 3.4. Display the dictionary
print("D2 = ", D2)

# 3.5. Close the file
f.close()

The result of the program

D2 = {1: 'Sun', 2: 'Mon', 3: 'Tue', 4: 'Wed', 5: 'Thu', 6: 'Fri', 7: 'Sat'}

View of file myfile6.txt

1:Sun
2:Mon
3:Tue
4:Wed
5:Thu
6:Fri
7:Sat

 

6. Read/write two-dimensional matrix of integers, presented in the form of a list

The example demonstrates writing and reading a two-dimensional matrix of integers of dimension 3*4.

# Writing/reading a two-dimensional matrix of numbers
# 1. The original matrix of integers 3*4 in size
M = [ [ 2, 1, -3],
      [ 4, 8, -2],
      [ 1, 2,  3],
      [ 7, -3, 8] ]

# 2. Writing a matrix to a text file
# 2.1. Open text file for writing
f = open('myfile8.txt', 'w')

# 2.2. The cycle of writing matrix elements to a file
#     in a convenient form
i = 0
while i < 4: # bypass rows in cycle
    j = 0
    while j < 3: # bypass columns in loop
        s = str(M[i][j])
        f.write(s + ' ') # between numbers symbol ' ' space
        j = j+1
    f.write('\n')
    i = i + 1

# 2.3. Close the file
f.close()

# 3. Read matrix from file
# 3.1. Open file for reading
f = open('myfile8.txt', 'rt')

# 3.2. Create empty list
M2 = []

# 3.3. Reading data from file and creating a new matrix
i = 0
for line in f: # Use a file iterator
    # Convert line to lines list
    lines = line.split(' ')

    # temporary list
    lst = []

    # traversing elements in lines
    for ln in lines:
        # remove the character '\n'
        ln = ln.rstrip()

        if ln != '':
            num = int(ln) # get a single number
            lst = lst + [num] # add a number to the list

    M2 = M2 + [lst] # add a line to the resulting matrix

# 3.4. Display M2 matrix
print("M2 = ", M2)

# 3.5. Close the file
f.close()

The result of the program

M2 = [[2, 1, -3], [4, 8, -2], [1, 2, 3], [7, -3, 8]]

View of the file myfile8.txt

2 1 -3
4 8 -2
1 2 3
7 -3 8

 

7. Read/write a set that contains integers

The example shows a possible way to save the set in a text file.

# Writing/reading of the set in the text file.
# 1. Multiple integer objects specified
M = { 2, 3, -12, 22, 38 }

# 2. Writing a set to a file
# 2.1. Open text file for writing
f = open('myfile7.txt', 'w')

# 2.2. The cycle of writing set elements to a file
for item in M:
    # 2.2.1. Convert element of set to a string + '\n'
    s = str(item) + '\n'

    # 2.2.2. Write a string to a file
    f.write(s)

# 2.3. Close the file
f.close()

# 3. Reading set from a file
# 3.1. Открыть файл для чтения
f = open('myfile7.txt', 'rt')

# 3.2. Create an empty set
M2 = set()

# 3.3. Reading data from a file and creating a new set
for line in f: # Using file iterator
    # Convert line to integer
    num = int(line)
    M2 = M2.union({num})

# 3.4. Display the set
print("M2 = ", M2) # M2 =   {2, 3, -12, 38, 22}

# 3.5. Close the file
f.close()

The result of the file

M2 = {2, 3, -12, 38, 22}

The view of myfile7.txt file

2
3
38
-12
22


 

8. Read/write data of different types: list and tuple

To write data of different basic types to a text file, you need to sequentially write data of one type, then another type. When reading such data, one must adhere to this very order so as not to violate the resulting data structure.

The example demonstrates sequential writing to a list file and tuple. When reading, it follows the same sequence: first the list is read, then the tuple. The list includes strings. To facilitate the recognition of the file format, each written (readable) element is placed on a separate line in the file. Since the list and tuple may contain a different number of elements, their dimensions are written to the file.

 

# Writing/reading data of various types.
# List and tuple processing.
# 1. Given a list of strings and a tuple of numbers
L = [ 'John Johnson', 'Peter Petrov', 'O Neill', 'J. Dunkan' ]
T = ( 2, 3.85, 7.77, -1.8, 5.25 )

# 2. Writing data to a file: first a list is written, then a tuple
# 2.1. Open text file for writing
f = open('myfile9.txt', 'w')

# 2.2. Write the number of list items + '\n'
f.write(str(len(L)) + '\n')

# 2.3. The cycle of writing list items to a file
#     Each of the list items is placed on a new line.
for item in L: # обход списка
    f.write(item + '\n')

# 2.4. After the list, a tuple is written,
#     each element of the tuple is placed on a separate line.
#     First write down the number of tuple elements
f.write(str(len(T)) + '\n')

# bypassing the tuple in the cycle
for item in T:
    f.write(str(item) + '\n') # write elements

# 2.3. Close the file
f.close()

# 3. Reading list and tuple from file
# 3.1. Open file for reading
f = open('myfile9.txt', 'rt')

# 3.2. Create resulting empty list
#     and the resulting tuple
L2 = []
T2 = ()

# 3.3. Reading data from a file and forming a list of L2
n = int(f.readline()) # read number of items

i = 0
while i < n: # cycle of reading lines from a file and forming a list
    s = f.readline().rstrip() # read a line without the character '\n'
    if (s != ''):
        L2 += [s]
    i = i + 1

# 3.4. read the number of items of tuple
n = int(f.readline())

i = 0
while i < n: # the loop of strings reading and tuple formation
    s = f.readline()
    if (s != ''):
        T2 = T2 + (float(s),) # add a real number to the tuple
    i = i+1

# 3.5. Close the file
f.close()

# Display list and tuple
print("L2 = ", L2)
print("T2 = ", T2)

The result of the program

L2 = ['John Johnson', 'Peter Petrov', 'O Neill', 'J. Dunkan']
T2 = (2.0, 3.85, 7.77, -1.8, 5.25)

The view of myfile9.txt file

4
John Johnson
Peter Petrov
O Neill
J. Dunkan
5
2
3.85
7.77
-1.8
5.25

 


Related topics