Python. Text files. Examples of processing (modification) of text files in accordance with the condition

Text files. Examples of solving tasks on modifying text files

This topic provides examples of solving problems that may arise when processing text files. The approach to operating data in files proposed in this topic can be used to solve a wide range of related tasks.


Contents


Search other websites:




1. How to determine if the data in a text file has run out?

Python uses the readline() method to read a string. If this method returns an empty string , then this is a sign of the end of the file.

Example.

# Calculate the number of lines in a file
# 1. Open text file for reading
f = open('TextFile1.txt', 'r')

# 2. Cycle of reading lines in a file
count = 0 # the number of lines in a file
s = f.readline()

while s != '':       # read lines to empty line
  s = f.readline()
  count = count+1

print('count = ', count) # display the result

# 3. Close the file
f.close()

 

2. How to read lines from a text file if their number is unknown? Ways to determine the number of lines in a file

There are two main ways to read all lines of a file:

  • read lines of a file using readlines() method. The result will be a list. Then use the len() method to determine the number of lines;
  • implement a read line loop using readline() until there is no empty line. The readline() method returns an empty string when the end of the file is reached.

Example. The example shows 3 ways to determine the number of lines in a file.

# Determining the number of lines in a file
# Method 1. The readline() method.
# 1.1. Open text file for reading
f = open('TextFile1.txt', 'r')

# 1.2. Cycle of reading lines in a file
count = 0 # number of lines in a file
s = f.readline()

while s != '':       # read line to empty line
    s = f.readline()
    count = count+1

print('count = ', count) # display the result

# 1.3. Close the file
f.close()

# ----------------------------------
# Method 2. The readlines() method
# 2.1. Open text file for reading
f = open('TextFile1.txt', 'r')

# 2.2. Read file lines to list L
L = f.readlines()

# 2.3. The number of list items == the number of lines in the file
count = len(L)
print('count = ', count)

# 2.4. Close the file
f.close()

# -------------------------------------
# Способ 3. Using a file iterator
# 3.1. Open text file for reading
f = open('TextFile1.txt', 'r')

# 3.2. Use a file iterator
count = 0
for line in f: count = count+1

# 3.3. Display the result
print('count = ', count)

# 3.4. Close the file
f.close()

 

3. Replacing the string in a text file. Example

To replace a line in a text file, do the following:

  • read the file to the list;
  • change the line in the list;
  • write the list to a file.

 

# Replacing the line in a text file
# 1. Source line
s = "Hello world!"

# 2. Specified position (number from 0)
pos = 3

# 3. Open file for reading
f = open('TextFile1.txt', 'r')

# 4. Read all lines from file to list L
L = f.readlines()

# 5. Replace the line in the list at pos
if (pos >= 0) and (pos < len(L)):
    # in the last line '\n' do not add
    if (pos==len(L)-1):
        L[pos] = s
    else:
        L[pos] = s + '\n'

# 6. Close the file
f.close()

# ------------------------------------
# Write modified list to file

# 7. Open file for reading
f = open('TextFile1.txt', 'w')

# 8. Write the list
for line in L:
    f.write(line)

# 9. Close the file
f.close()

 

4. Removing a line from a file by its index. Example

Following the example of paragraph 3, a line is deleted by its index.

# Removing a line from a file by index
# 1. Enter delete position (numbered from 0)
pos = int(input('pos = '))

# 2. Open file for reading
f = open('TextFile1.txt', 'r')

# 3. Read all lines from file to list L
L = f.readlines()

# 4. Remove line from the list
# Check if pos position is correct
if (pos >= 0) and (pos < len(L)):
    i = pos
    while i<len(L)-1:
        L[i] = L[i+1]
        i = i+1
    L = L[:-1] # remove the last item in the list

# 5. Close the file
f.close()

# ------------------------------------
# Write modified list to file
# 6. Open file for writing
f = open('TextFile1.txt', 'w')

# 7. Write the list
for line in L:
    f.write(line)

# 8. Close the file
f.close()

 

5. Inserting a line in the specified file position. Example

In this example, a line is inserted at the specified file position. If you specify the position that is located behind the last line of the file, then the line is appended to the end of the file.

# Insert a line at a given file position
# 1. Display the string
s = str(input('s = '))

# 2. Enter the insertion position (numbered from 0).
#   If the position is equal to the number of lines in the file,
#   then the line is appended to the end of the file.
pos = int(input('pos = '))

# 3. Open text file for reading
f = open('TextFile1.txt', 'r')

# 4. Read all lines from file to list L
L = f.readlines()

# 5. Check if pos value is correct
if (pos<0) or (pos>len(L)):
    f.close()
    exit()

# 6. Check if pos is the line that follows the last line
if pos==len(L):
    # need to add a line to the end of the list L
    L[len(L)-1] += '\n'
    L2 = L + [s] # add the string s to the end of the list L
else:
    # Create a new list L2 that will contain a list L
    # with a new line s inserted at position pos.
    L2 = []

    # Copy items from L to L2 to the paste position
    L2 = L2 + L[:pos] # use slice (!!!)

    # Insert s + a new line into the L2 list
    L2 = L2 + [s + '\n']

    # Copy from L to L2 elements that lie after pos
    L2 = L2 + L[pos:] # again use the slice

# 7. Close the file
f.close()

# ------------------------------------
# Write newly created L2 list to file
# 8. Open file for writing
f = open('TextFile1.txt', 'w')

# 9. Write list L2
for line in L2:
    f.write(line)

# 10. Close the file
f.close()

 

6. Swap two lines in a file. Example

When reading a list from a file, the last line of the list may be with the character ‘\n’ at the end or without it. This feature must be taken into account in the program.

# Swap two lines in a file
# 1. Enter the position of line 1 (numbered from 0)
pos1 = int(input('pos1 = '))

# 2. Enter the position of line 2 (numbered from 0), pos2>pos1
pos2 = int(input('pos2 = '))

# 3. Check condition: pos2>pos1
if pos2<=pos1: exit()

# 4. Open text file for reading
f = open('TextFile1.txt', 'r')

# 5. Read all lines from file to list L
L = f.readlines()

# 6. Correction of the last line - add '\n' if necessary
s = L[len(L)-1] # get the last line
length = len(s) # get the length of last line
f_nl = True

if (length>0)and((s[length-1] != '\n')):
    L[len(L)-1] += '\n' # add the last line '\n'
    f_nl = False

# 7. Close the file
f.close()

# 8. Check if pos1 and pos2 are set correctly
if (pos1<0)or(pos1>=len(L))or(pos2<0)or(pos2>=len(L)):
    exit()

# 9. Swap strings
s = L[pos1]
L[pos1] = L[pos2]
L[pos2] = s

# ------------------------------------
# Write newly created list L to file
# 10. Open file for writing
f = open('TextFile1.txt', 'w')

# 11. If at the end of the file there was no '\n'
if f_nl == False:
    # then remove from the last line '\n'
    L[len(L)-1] = L[len(L)-1][:-1]

# 12. The cycle of writing each line of the list to a file
for item in L:
    f.write(item)

# 13. Close the file
f.close()

 

7. Reversing file lines (rearranging file lines in reverse order). Example

 

# Rearrange file lines in reverse order
# 1. Open text file for reading
f = open('TextFile1.txt', 'r')

# 2. Read all lines from file to list L
L = f.readlines()

# 3. Correction of the last line - add '\n' if necessary
s = L[len(L)-1] # get the last line
length = len(s) # get tht length of last line
f_nl = True # flag indicating whether the character '\n' was at the end of the file

if (length>0)and((s[length-1] != '\n')):
    L[len(L)-1] += '\n' # add to the last line '\n'
    f_nl = False

# 4. Close the file
f.close()

# 5. Create a new list L2 - reverse to list L
L2=[]
i=0
while i<len(L):
    s = L[len(L)-i-1] # take line from end of list L
    L2 = L2 + [s]
    i = i+1

# 6. If at the end of the file there was no '\n'
if f_nl == False:
    # then remove from the last line '\n'
    L2[len(L)-1] = L2[len(L)-1][:-1]

# ------------------------------------
# Write newly created L2 list to file
# 7. Open file for writing
f = open('TextFile1.txt', 'w')

# 8. The cycle of writing each line of the list to a file
for item in L2:
    f.write(item)

# 11. Close the file
f.close()

 

8. Sort file lines. The method of selection sorting. Example

An example of sorting file lines is provided. The selection sorting method is used.

# Sort file lines. Selection sort method
# 1. Open text files for reading
f = open('TextFile1.txt', 'r')

# 2. Read all lines from file to list L
L = f.readlines()

# 3. Correction of the last line - add '\n' if necessary
s = L[len(L)-1] # get the last line
length = len(s) # get the length of last line
f_nl = True # flag indicating whether the character '\n' was at the end of the file

if (length>0)and((s[length-1] != '\n')):
    L[len(L)-1] += '\n' # add to the last line '\n'
    f_nl = False

# 4. Close the file
f.close()

# 5. Selection sort of list L
i=0
while i<len(L):
    k = i

    # minimal element search
    x = L[i]

    j=i+1
    while j<len(L):
        if L[j]<x:
            k = j
            x = L[j]
            j=j+1

    # Swap the smallest element of L[i]
    L[k] = L[i]
    L[i] = x
    i=i+1

# 6. Consider if there was a '\n' character at the end
if f_nl == False:
    # then remove from the last line '\n'
    L[len(L)-1] = L[len(L)-1][:-1]

# ------------------------------------
# Write newly created list L to file
# 7. Open file for writing
f = open('TextFile1.txt', 'w')

# 8. The cycle of writing each line of the list to a file
for item in L:
    f.write(item)

# 9. Close the file
f.close()

 

9. Merge two files. Example

 

# -----------------------
# Merge files myfile1.bin+myfile2.bin => myfile3.bin
# 1. Open file for reading
f1 = open('myfile1.bin', 'rb')
f2 = open('myfile2.bin', 'rb')

# 2. Read files to lists L1, L2
L1 = f1.readlines()
L2 = f2.readlines()

# 3. Merge lists
L3 = L1 + L2

# 4. Close files myfile1.bin, myfile2.bin
f1.close()
f2.close()

# 5. Open file myfile3.bin for writing
f3 = open('myfile3.bin', 'wb')

# 6. Write lines to the file
f3.writelines(L3)

# 7. Close the resulting file
f3.close()

 


Related topics

 


 

0
fb-share-icon20