Read and save data from the _python Python series from a file

Source: Internet
Author: User

Download all the files in the Headfirstpython Web site and extract the "Sketch.txt" in Chapter 3 as an example:

Create a new idle session, import the OS module first, and swap the working directory for the folder that contains the file "Sketch.txt", such as C:\\python33\\headfirstpython\\chapter3

Copy Code code as follows:

>>> Import OS
>>> OS.GETCWD () #查看当前工作目录
' C:\\python33 '
>>> os.chdir (' C:/python33/headfirstpython/chapter3 ') #切换包含数据文件的文件夹
>>> OS.GETCWD () #查看切换后的工作目录
' C:\\python33\\headfirstpython\\chapter3 '

Open the file "Sketch.txt" to read and display the first two lines:

Copy Code code as follows:

>>> data=open (' Sketch.txt ')
>>> print (Data.readline (), end= ')
Man:is This right room for a argument?
>>> print (Data.readline (), end= ')
Other man:i ' ve told you once.

Back to the beginning of the file, use the For statement to process each line in the file, and then close the file:

Copy Code code as follows:

>>> data.seek (0) #使用seek () method back to the beginning of the file
>>> for Each_line in data:
Print (each_line,end= ')


Man:is This right room for a argument?
Other man:i ' ve told you once.
Man:no you haven ' t!
Other Man:yes I have.
Man:when?
Other man:just now.
Man:no you didn ' t!
Other Man:yes I did!
Man:you didn ' t!
Other man:i ' m telling for you, I did!
Man:you did not!
Other Man:oh I ' m Sorry, are this a five minute argument, or the full half hour?
man:ah! (taking out his wallet and paying) Just the five minutes.
The other man:just the five minutes. Thank you.
Other Man:anyway, I did.
Man:you most certainly did not!
Other Man:now let ' s get one thing quite clear:i most definitely told you!
Man:oh no you didn ' t!
Other Man:oh Yes I did!
Man:oh no you didn ' t!
Other Man:oh Yes I did!
Man:oh look, this is isn ' t an argument!
(pause)
Other Man:yes it is!
Man:no it isn ' t!
(pause)
Man:it ' s just contradiction!
Other man:no it isn ' t!
Man:it is!
Other Man:it is not!
Man:you just contradicted me!
Other man:no I didn ' t!
Man:you did!
Other Man:no No no!
Man:you did just then!
Other man:nonsense!
Mans: (exasperated) Oh, this is futile!!
(pause)
Other man:no it isn ' t!
Man:yes it is!
>>> Data.close ()

After reading the file, save the different role corresponding data to the list man and other:

Copy Code code as follows:

Import OS
Print (OS.GETCWD ())
Os.chdir (' C:\Python33\HeadFirstPython\chapter3 ')
Man=[] #定义列表man接收Man的内容
Other=[] #定义列表other接收Other man's content

Try
Data=open ("Sketch.txt")
For Each_line in data:
Try
(role, Line_spoken) =each_line.split (': ', 1)
Line_spoken=line_spoken.strip ()
If role== ' man ':
Man.append (Line_spoken)
Elif role== ' Other mans ':
Other.append (Line_spoken)
Except ValueError:
Pass
Data.close ()
Except IOError:
Print (' The datafile is missing! ')
Print (MANS)
Print (Other)

Tips:

When you open a disk file using the open () method, the default access mode is R, which means read, and does not need to be deliberately specified;

To open a file to write, you need to specify the mode W, such as Data=open ("Sketch.txt", "w"), and if the file already exists, the existing content is emptied;

To append to a file, you specify mode A, and the existing content is not emptied;

To open a file to write and read without emptying the existing content, you need to specify a pattern w+;

For example, if you save the man and other content saved in the previous example as a file, you can modify the following:

Copy Code code as follows:

Import OS
Print (OS.GETCWD ())
Os.chdir (' C:\Python33\HeadFirstPython\chapter3 ')
Man=[]
Other=[]

Try
Data=open ("Sketch.txt")
For Each_line in data:
Try
(role, Line_spoken) =each_line.split (': ', 1)
Line_spoken=line_spoken.strip ()
If role== ' man ':
Man.append (Line_spoken)
Elif role== ' Other mans ':
Other.append (Line_spoken)
Except ValueError:
Pass
Data.close ()
Except IOError:
Print (' The datafile is missing! ')

Try
Man_file=open (' Man.txt ', ' W ') #以w模式访问文件man. txt
Other_file=open (' Other.txt ', ' W ') #以w模式访问文件other. txt
Print (man, file=man_file) #将列表man的内容写到文件中
Print (Other, file=other_file)
Except IOError:
Print (' File error ')
Finally
Man_file.close ()
Other_file.close ()

But why does the 26th line print () make an error? "Syntax error while detecting tuple", there is a great God can give a break

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.