Python Learning 15:open reading files

Source: Internet
Author: User

I have studied raw_input and argv before, and in this section of Python learning, I learned how to use a script to open an ordinary text file, read it, and close the file. It is important to close the file in order to release resources and prevent the memory from being exhausted, causing the machine to deadlock. In addition, closing a file also has a role when writing a file, closing the contents of the buffer to the file itself.

The following is a simple script to read a text file.
We can implement this in two ways:
The first is a script with parameters.
The second is a script that uses variables directly to read a file without using parameters.

The first type:

1. # 导入argv模块2. from sys import argv3. # 定义变量名4. script, filename = argv5. # 定义txt变量存储打开文件后的内容6. txt = open(filename)7. # 输出打开的文件名,使用read模块读取txt变量内容然后打印出来。8. print "Here is your file %r: " % filename9. print txt.read()10. # 使用raw_input读取用户输入的文件名11. # 这里有个疑问?12. print "Type the filename again: "13. file_again = raw_input("> ")14. # 使用txt_again变量存储打开用户输入的文件的内容15. txt_again = open(file_again)16. # 通过read模块读取txt_again的内容,然后打印出来17. print txt_again.read()

The code line 13th has a question, why can the script recognize the input is the file under the current directory? Perhaps later to understand the deeper can answer this question.

The second type:

# 使用变量定义一个提示语句,然后在raw_input中去调用这个变量,这样使得代码能够更加简洁,缺点是变量也要占用内存空间。prompt = ‘Please input a filename > ‘txt = raw_input(prompt)# 打开文本,并用一个变量保存txt_open = open(txt)# 在这里把内容直接读到内存里并打印出来,不使用变量来保存print txt_open.read()txt_open.close()txt_input = raw_input(prompt)txt1 = open(txt_input)print txt1.readline()txt1.close()

Python Learning 15:open reading files

Related Article

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.