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

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.

主站蜘蛛池模板: 康定县| 台前县| 开远市| 锦屏县| 贵溪市| 驻马店市| 久治县| 滨州市| 万山特区| 兴化市| 湖南省| 牙克石市| 宜阳县| 仙桃市| 贵定县| 岐山县| 宾川县| 山丹县| 西贡区| 侯马市| 泸西县| 乃东县| 吉隆县| 双流县| 定安县| 邓州市| 临朐县| 石家庄市| 宽城| 江安县| 安远县| 兴和县| 旬阳县| 五华县| 新营市| 察哈| 来凤县| 张家口市| 漾濞| 湘潭县| 望谟县|