A happy journey of simple Python: file manipulation of Python basic syntax

Defonds 2020-11-13 04:52:44
happy journey simple python file



This topic will read files or folders 、 write in 、 Additional 、 to update 、 Delete and other operations to explain .

1. Read text file

stay Python Can be used in open() Function to open a file , This function will return a file object , Then we can call the read() Function to read its contents .
In the catalog D:\work\20190810 Next new file , Edit it to Hello Python~ After saving . Perform the following Python Code :

# Python Program to Read Text File
f = open("D:/work/20190810/sample.txt", "r")
data = f.read()
print(type(f))
print(type(data))
print(data)

Output results :
 Read text file .png

1.1. Read individual characters in a text file

In the example above , Pay attention to the absolute path , If you give the relative path , Take the directory where the program is executed as the current directory .
If you only want to read the starting N Characters , The digital N As a parameter to read() Function .

# Read only some characters in the Text File
f = open("D:/work/20190810/sample.txt", "r")
data = f.read(7)
print(data)

Execution and output :
 Read individual characters in a text file .png
The top read before 7 Characters , so N With 1 Start .

1.2. Read files in text mode

By default , When you open a file , The file will be opened in text mode . Another open mode is called binary mode . In the next example , We will use “t” and “r” Together , Open the file explicitly in text-only mode .

# Read file in Text mode
f = open("D:/work/20190810/sample.txt", "rt")
data = f.read()
print(data)

Execution and output :
 Read files in text mode .png

2. Write string to text file

To write a string to a text file , You can follow these steps :

  • Use open() Function to open a file in write mode
  • Using the write() Method to write a string to
  • Using the close() Method to close the file

2.1. Write string to text file

In the next example , We will follow the steps above to write a string constant to a text file .

# Write String to Text File
text_file = open("D:/work/20190810/sample.txt", "w")
n = text_file.write('Python welcome you~')
text_file.close()
print(n)

Execute the example :
 Write string to text file .png
so write() Method returns the number of characters contained in the string written to the text file .
Open the file with a text editor to see what it says as follows :
 File after writing string .png
After the text file is opened in write mode , And write it , If the file already exists , The original content will be overwritten . If the file does not exist , Will create a new file and write the string to .

2.2. Write string to text file in text mode

We mentioned in the last section , A file can be opened in one of two modes : Text or binary . By default a file will open in text mode , Of course, you can also explicitly define the use of text mode to open . In the next example , We will use “t” To explicitly open a file in text mode , And follow the steps above to write the string to the file .

# Write String to Text File in Text Mode
text_file = open("D:/work/20190810/sample.txt", "wt")
n = text_file.write('Python, Python~')
text_file.close()
print(n)

Execution and output :
 Write string to text file in text mode .png
Open the file again to see its contents :
 Open the file again to see its contents .png

3. remove file

stay Python To remove a file, you can call os Library remove() Method , Pass the path of the file to it as a parameter .

3.1. remove file

In the next example , We delete the files used in the previous section .

# Remove File with Python
import os
os.remove("D:/work/20190810/sample.txt")
print("The file is removed")

Execution and output :
 remove file .png
Comparison of files under the directory where the file is located before and after deletion :
 Before and after deletion .png

3.2. Remove nonexistent files

If provided to remove() Method does not exist , You're going to get a FileNotFoundError error .
Perform the above deletion procedure again , Output :
 Remove nonexistent files .png

4. Create directory

stay Python Create a new directory in the program. You can use os.mkdir() function , Pass the path to the directory you want to create .
os.mkdir() The syntax of the function is as follows :

os.mkdir(path, mode=0o777, *, dir_fd=None)

among path It's the path mentioned above ,mode For the file permissions assigned to this directory . Please refer to linux File authority system ,777 Read, write, and execute permissions for all users .

4.1. Create directory

In the next example, we'll create a new one called sample The catalog of .

# Create a Directory or Folder with Python
import os
os.mkdir("D:/work/20190810/sample")
print('The directory is created.')

Execution and output :
 Create directory .png
Compare the parent directory of the folder before and after execution :
 The parent directory where the folder is located .png

4.2. Create an existing directory

If you want to create an existing directory , You're going to get a FileExistsError.
Continue to create the directory in the previous section. The output is as follows :
 Create an existing directory .png
The error indicates When the file already exists , Unable to create the file .: ‘D:/work/20190810/sample’, At the same time, it also prompts which line of code in which the error occurred File “D:/PycharmProjects/MyPythonApp/testfile.py”, line 8, in <module>.

5. Check whether the specified path is a file or a directory

To check whether the given path is a file or a directory , Use os Library isfile() Method to check whether it is a file ,isdir() Method to check whether it is a directory .

import os
isFile = os.path.isfile(fpath)
isDirectory = os.path.isdir(fpath)

Both methods will return a Boolean value , Indicates whether the file path is a file , Or whether it's a directory .

5.1. Check whether the specified path is a file

Next, we will execute the above code to write sample.txt Create good , Then judge whether it is a file .

# Check if the Path is a File
import os
fpath = "D:/work/20190810/sample.txt"
isFile = os.path.isfile(fpath)
print("The file present at the path is a regular file:", isFile)

Execution and output :
 Determine whether it is a document .png
Now let's determine whether the parent directory is a file .

# try with a path that is a folder
fpath = "D:/work/20190810"
isFile = os.path.isfile(fpath)
print("The file present at the path is a regular file:", isFile)

Execution and output :
 Determine whether its parent directory is a file .png
great , We can determine whether the specified path is a file .

5.2. Check whether the specified path is a directory

In the next example , We use isdir() Method to determine whether the specified path is a directory .

# Check if the Path is a Directory
fpath = "D:/work/20190810"
isDirectory = os.path.isdir(fpath)
print("Path points to a Directory:", isDirectory)
fpath = "D:/work/20190810/sample.txt"
isDirectory = os.path.isdir(fpath)
print("Path points to a Directory:", isDirectory)

Execution and output :
 Check whether the specified path is a directory .png

6. Get a list of all the files in the directory and its subdirectories

To get a folder / Directory and its subfolders / A list of all the files in the subdirectory , We can use os.walk() function .os.walk() Function will provide the current directory 、 An iteration of subdirectories and all the files under them .

6.1. Get a list of all the files

In this example , Let's get a directory path first , Next, recursively enumerate all the files in the directory and its subdirectories .

# Get the list of all files
import os
path = "D:\PycharmProjects\MyPythonApp"
for root, dirs, files in os.walk(path):
for file in files:
print(os.path.join(root,file))

The output of the program is as follows :

D:\PycharmProjects\MyPythonApp\venv\Scripts\python.exe
D:/PycharmProjects/MyPythonApp/testfile.py
D:\PycharmProjects\MyPythonApp\Car.py
D:\PycharmProjects\MyPythonApp\first.py
D:\PycharmProjects\MyPythonApp\inputtest.py
D:\PycharmProjects\MyPythonApp\testfile.py
D:\PycharmProjects\MyPythonApp\testkeywords.py
D:\PycharmProjects\MyPythonApp\testlist.py
D:\PycharmProjects\MyPythonApp\testobject.py
D:\PycharmProjects\MyPythonApp\.idea\encodings.xml
D:\PycharmProjects\MyPythonApp\.idea\misc.xml
D:\PycharmProjects\MyPythonApp\.idea\modules.xml
D:\PycharmProjects\MyPythonApp\.idea\MyPythonApp.iml
D:\PycharmProjects\MyPythonApp\.idea\workspace.xml
D:\PycharmProjects\MyPythonApp\venv\pyvenv.cfg
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\easy-install.pth
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\setuptools-39.1.0-py3.7.egg
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\setuptools.pth

All subdirectories under the specified directory can be seen , Subdirectories of subdirectories , Subdirectories of subdirectories subdirectories of subdirectories … All of the documents below have been printed out .
To understand the execution of the above procedures , Just perform the following procedure :

# Get the list of all files with a specific extension
import os
path = "D:\PycharmProjects\MyPythonApp"
for root, dirs, files in os.walk(path):
print(root)
print(dirs)
print(files)

The output after execution is as follows :

D:\PycharmProjects\MyPythonApp\venv\Scripts\python.exe
D:/PycharmProjects/MyPythonApp/testfile.py
D:\PycharmProjects\MyPythonApp
['.idea', 'venv']
['Car.py', 'first.py', 'inputtest.py', 'testfile.py', 'testkeywords.py', 'testlist.py', 'testobject.py']
D:\PycharmProjects\MyPythonApp\.idea
[]
['encodings.xml', 'misc.xml', 'modules.xml', 'MyPythonApp.iml', 'workspace.xml']
D:\PycharmProjects\MyPythonApp\venv
['Include', 'Lib', 'Scripts']
['pyvenv.cfg']
D:\PycharmProjects\MyPythonApp\venv\Include
[]
[]

Python Source code os.py Yes walk The definition is as follows :

Directory tree generator.
For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple
dirpath, dirnames, filenames
dirpath is a string, the path to the directory. dirnames is a list of
the names of the subdirectories in dirpath (excluding '.' and '..').
filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists are just names, with no path components.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).

6.2. Get a list of all files with the specified extension

Based on the example in the previous section , We'll call all extensions .py The file is filtered out and printed .

# Get the list of all files with a specific extension
import os
path = "D:\PycharmProjects\MyPythonApp"
for root, dirs, files in os.walk(path):
for file in files:
if (file.endswith(".py")):
print(os.path.join(root, file))

The output after execution :

D:\PycharmProjects\MyPythonApp\venv\Scripts\python.exe
D:/PycharmProjects/MyPythonApp/testfile.py
D:\PycharmProjects\MyPythonApp\Car.py
D:\PycharmProjects\MyPythonApp\first.py
D:\PycharmProjects\MyPythonApp\inputtest.py
D:\PycharmProjects\MyPythonApp\testfile.py
D:\PycharmProjects\MyPythonApp\testkeywords.py
D:\PycharmProjects\MyPythonApp\testlist.py
D:\PycharmProjects\MyPythonApp\testobject.py
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\__init__.py
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\__main__.py

6.3. File traversal

In the following example, we traverse and count the space occupied by files in the specified directory , Check which subdirectory takes up more space , Can be implemented similar to linux Of du Effect of command , Disk space monitoring system can be applied in real time . This is very important for system operation and maintenance , Because disk monitoring is an important part of system operation monitoring and abnormal real-time alarm KPI.

# Get the size of all directories of specific directory
import os
from os.path import join, getsize
path = "D:\PycharmProjects\MyPythonApp"
for root, dirs, files in os.walk(path):
print(root, "directory takes", sum([getsize(join(root, name)) for name in files]), "bytes")

Output the result after execution :

D:\PycharmProjects\MyPythonApp\venv\Scripts\python.exe
D:/PycharmProjects/MyPythonApp/testfile.py
D:\PycharmProjects\MyPythonApp directory takes 8575 bytes
D:\PycharmProjects\MyPythonApp\.idea directory takes 21842 bytes
D:\PycharmProjects\MyPythonApp\venv directory takes 81 bytes
D:\PycharmProjects\MyPythonApp\venv\Include directory takes 0 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib directory takes 0 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages directory takes 563301 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg directory takes 0 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\EGG-INFO directory takes 15653 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip directory takes 653 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_internal directory takes 227304 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_internal\commands directory takes 82597 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_internal\models directory takes 518 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_internal\operations directory takes 29549 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_internal\req directory takes 82600 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_internal\utils directory takes 77945 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_internal\vcs directory takes 44880 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor directory takes 425914 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\cachecontrol directory takes 37555 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\cachecontrol\caches directory takes 5435 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\certifi directory takes 272070 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\chardet directory takes 370901 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\chardet\cli directory takes 2861 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\colorama directory takes 26810 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\distlib directory takes 768144 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\distlib\_backport directory takes 153388 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\html5lib directory takes 358491 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\html5lib\filters directory takes 47191 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\html5lib\treeadapters directory takes 4304 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\html5lib\treebuilders directory takes 55339 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\html5lib\treewalkers directory takes 28632 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\html5lib\_trie directory takes 4334 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\idna directory takes 244485 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\lockfile directory takes 30251 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\msgpack directory takes 40249 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\packaging directory takes 59842 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\pkg_resources directory takes 107226 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\progress directory takes 12243 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\pytoml directory takes 15475 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\requests directory takes 171402 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\urllib3 directory takes 124905 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\urllib3\contrib directory takes 69295 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\urllib3\contrib\_securetransport directory takes 30558 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\urllib3\packages directory takes 40274 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\urllib3\packages\backports directory takes 1514 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\urllib3\packages\ssl_match_hostname directory takes 6583 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\urllib3\util directory takes 79210 bytes
D:\PycharmProjects\MyPythonApp\venv\Lib\site-packages\pip-10.0.1-py3.7.egg\pip\_vendor\webencodings directory takes 32843 bytes
D:\PycharmProjects\MyPythonApp\venv\Scripts directory takes 1426147 bytes

7. Append text to file

stay Python You need to add text to the file as follows .

  1. Use a+ Mode open file .
  2. Write or append text to a file .
  3. Close file .

7.1. Append text to file

In the next example , We first created a... With some text data.txt file . We will follow the above steps to add some text to the file .
The content of the document is :
 The original document .png
Edit writer :

# Concatenate or Append Text to File
fin = open("D:/work/20190810/data.txt", "a+")
fin.write("\nThis is newly append text.")
fin.close()

Execute the program , Look at the file again :
 The new text has been written in .png

7.2. Append text to file in text mode

You can process files in either text or binary mode . By default , Files are processed in text mode . In the next example , We will add “t” To “a” The latter approach explicitly processes files in text mode .

# Append Text to File in Text Mode
fin = open("D:/work/20190810/data.txt", "at")
fin.write("\nThis is newly append text.")
fin.close()

Check again after execution data.txt
 Add again .png

8. Replace the string in the file

To use Python Replace a string in the file , You can follow these steps :

  1. Open the input file in read-only mode and process it in text mode .
  2. Open the output file in write mode and process it in text mode .
  3. Read the input file line by line , After replacing the string, write the line to the output file .
  4. Turn off input and output files .

8.1. Replace the string in the file

newly build input.txt And edit its contents as follows :
 Input file .png
Perform the following Python Program :

# Replace string in File
fin = open("D:/work/20190810/input.txt", "rt")
fout = open("D:/work/20190810/out.txt", "wt")
for line in fin:
fout.write(line.replace("pyton", "python"))
fin.close()
fout.close()

After successful execution , New files found in this directory out.txt Generate , View its contents :
 The output file .jpg
What happened? ?

  1. With rt Mode on input.txt And fin The reference points to the file object .
  2. With wt Mode on / newly build out.txt And fout The reference points to the file object .
  3. for line in fin: about fin Every line in the document ,line.replace() take pyton Replace with python,fout.write Write in fout file .
  4. fin.close(): Reference objects through files fin Close the file ,fout.close(): Reference objects through files fout Close the file .

8.2. Replace strings in the same file

In the next example , We're right input.txt File operation , Will be one of the pyton Replace with python, And rewrite it with the replaced text input.txt.

# Replace string in the same File
fin = open("D:/work/20190810/input.txt", "rt")
data = fin.read()
data = data.replace("pyton", "python")
fin.close()
fin = open("D:/work/20190810/input.txt", "wt")
fin.write(data)
fin.close()

Check... After executing the program input.txt The contents are as follows :
 Replaced input file .jpg
What happened? ?

  1. In read-only text rt Mode open file input.txt.
  2. fin.read() take input.txt Read all the contents in and store them in variables data.
  3. data.replace() Within the scope of the full text, all pyton Replace with python.
  4. fin.close() take input.txt close .
  5. The last three lines of code , We write text again wt Mode on input.txt And will data The contents stored in are written in replacement mode input.txt, Finally, close the file .

9. Replace multiple consecutive spaces in a file with a single space

There are many ways to replace multiple spaces in a file with a single space , For example, using string segmentation or regular expressions . Let's use specific examples to learn about these methods .

9.1. Cut string

  1. Read the input text file in read-only mode , Open the output file in write mode .
  2. Read the input file line by line . First , Use split() Method to split a given string .split() By default, spaces are used as separators . When there are consecutive spaces , Extra space will be ignored, so we will get multiple independent words ; Use a single space to reassemble these separated strings ; Write output file .
  3. Close input and output files .

Next, let's start with the example above input.txt and out.txt Delete , Then build input.txt And edit its contents as follows :

Welcome to       www.defonds.net. Here, you will       find python programs            for all       general use cases.

Code example :

# Using Split String
fin = open("D:/work/20190810/input.txt", "rt")
fout = open("D:/work/20190810/out.txt", "wt")
for line in fin:
fout.write(' '.join(line.split()))
fin.close()
fout.close()

After executing the program, it was found that out.txt The generated , Its content is :

Welcome to www.defonds.net. Here, you will find python programs for all general use cases.

You can see , All consecutive spaces have been replaced by a single space .

9.2. Using regular expressions

We can also use regular expressions to find consecutive spaces , And replace them with a single space .

  1. Import re modular .re It's an abbreviation for regular expressions .
  2. Read the input text file in read-only mode , Open the output file in write mode .
  3. Read the input file line by line , And then use re.sub() Method , This method will replace the regular match string provided by the first parameter with the string provided by the second parameter . A regular expression that matches multiple consecutive spaces is \s+.
  4. Close input and output files .

An example of a program that uses regular to replace consecutive spaces into a single space is as follows :

# Using Regular Expression Replace
import re
fin = open("D:/work/20190810/input.txt", "rt")
fout = open("D:/work/20190810/out.txt", "wt")
for line in fin:
fout.write(re.sub("\s+", ' ', line))
fin.close()
fout.close()

10. How to count the number of words in a text file

To count the number of words that appear in a text file , The following steps need to be followed .

  1. Open the file in read-only mode and process it in text mode .
  2. Using the read() Function to read text content .
  3. Use spaces as separators to segment text .
  4. The length of the split string list gives the number of words .

10.1. Count the number of words

Create or edit data.txt The contents are as follows :

Welcome to www.defonds.net. Here, you will find python programs for all general use cases.
The procedure is as follows :
# Count Number of Words
file = open("D:/work/20190810/data.txt", "rt")
data = file.read()
words = data.split()
print("Number of words in text file:", len(words))

Execution and output :
 Count the number of words .png

10.2. Count the number of words in multiple lines of text

Re edit data.txt The content of , Add a line and read as follows :

Welcome to www.defonds.net. Here, you will find python programs for all general use cases.
This is another line with some words.

Still using the previous section code , Execution and output :
 Count the number of words in multiline text .png

11. How to count the number of characters in a text file

To count the number of characters in a text file , The following steps need to be followed .

  1. Open the file in read-only mode .
  2. Use read() Function to open text .
  3. Count the string length of the read text , This is the number of characters in the text file .

11.1. Count the number of characters in a text file

Create or edit data.txt The contents are shown below .

Welcome to www.defonds.net. Here, you will find python programs for all general use cases.
Related codes :
# Count Characters in a Text File
file = open("D:/work/20190810/data.txt", "r")
data = file.read()
number_of_characters = len(data)
print("Number of characters in text file:", number_of_characters)

Execution and output :
 Count the number of characters in a text file .png

11.2. Count the number of characters excluding spaces in the text file

Next, we'll try to count the number of characters in the file except for spaces .

# Count Characters in a Text File excluding spaces
file = open("D:/work/20190810/data.txt", "r")
data = file.read().replace(" ", "")
number_of_characters = len(data)
print("Number of characters in text file:", number_of_characters)

Execution and output :
 Count the number of characters excluding spaces in the text file .png

Reference material

版权声明
本文为[Defonds]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database