官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 吉安市| 六枝特区| 盐池县| 西畴县| 冷水江市| 阳信县| 瓦房店市| 石柱| 芜湖市| 务川| 泰安市| 博客| 唐河县| 中西区| 五莲县| 西畴县| 达日县| 霍州市| 通海县| 遂溪县| 东明县| 贺兰县| 康平县| 宝清县| 凌云县| 嘉义市| 汉源县| 泾源县| 杂多县| 富平县| 外汇| 蓝田县| 尚义县| 合肥市| 界首市| 垦利县| 南城县| 新丰县| 宣武区| 离岛区| 赤壁市|