- Hands-On Artificial Intelligence for IoT
- Amita Kapoor
- 378字
- 2021-07-02 14:01:59
Using TXT files in Python
Python has built-in functions that read and write into TXT files. The complete functionality is provided using four sets of functions: open(), read(), write(), and close(). As the names suggest, they are used to open a file, read from a file, write into a file, and finally close it. If you are dealing with string data (text), this is the best choice. In this section, we will use Shakespeare plays in TXT form; the file can be downloaded from the MIT site: https://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8.shakespeare.txt.
We define the following variables to access the data:
data_folder = '../../data/Shakespeare'
data_file = 'alllines.txt'
The first step here is to open the file:
f = open(data_file)
Next, we read the whole file; we can use the read function, which will read the whole file as one single string:
contents = f.read()
This reads the whole file (consisting of 4,583,798 characters) into the contents variable. Let's explore the contents of the contents variable; the following command will print the first 1000 characters:
print(contents[:1000])
The preceding code will print the output as follows:
"ACT I"
"SCENE I. London. The palace."
"Enter KING HENRY, LORD JOHN OF LANCASTER, the EARL of WESTMORELAND, SIR WALTER BLUNT, and others"
"So shaken as we are, so wan with care,"
"Find we a time for frighted peace to pant,"
"And breathe short-winded accents of new broils"
"To be commenced in strands afar remote."
"No more the thirsty entrance of this soil"
"will daub her lips with her own children's blood,"
"Nor more will trenching war channel her fields,"
"Nor bruise her flowerets with the armed hoofs"
"Of hostile paces: those opposed eyes,"
"Which, like the meteors of a troubled heaven,"
"All of one nature, of one substance bred,"
"Did lately meet in the intestine shock"
"And furious close of civil butchery"
"will now, in mutual well-beseeming ranks,"
"March all one way and be no more opposed"
"Against acquaintance, kindred and allies:"
"The edge of war, like an ill-sheathed knife,"
"No more will cut his master. Therefore, friends,"
"As far as to the sepulchre of Christ,"
"Whose
If the TXT files contain numeric data, it is better to use NumPy; if data is mixed, pandas is the best choice.
- 大學計算機信息技術導論
- TIBCO Spotfire:A Comprehensive Primer(Second Edition)
- Blockchain Quick Start Guide
- 計算機網絡應用基礎
- 工業機器人工程應用虛擬仿真教程:MotoSim EG-VRC
- VMware Performance and Capacity Management(Second Edition)
- Photoshop CS3圖層、通道、蒙版深度剖析寶典
- Nginx高性能Web服務器詳解
- The Python Workshop
- 悟透JavaScript
- 走近大數據
- MCGS嵌入版組態軟件應用教程
- 精通數據科學:從線性回歸到深度學習
- C++程序設計基礎(上)
- MPC5554/5553微處理器揭秘