Python 编程入门/Python 编程 - 处理文件
外观
Python 提供了更多输入和输出功能。“print”语句是最简单的产生输出的方法。
Python 解释器从终端读取输入时有两种方法,即
- raw_input
此命令无论输入的是表达式还是其他内容,都会将终端上的所有内容读取为输入,并返回一个字符串。
- 输入
input 命令将表达式作为常规的 Python 表达式进行评估,并将其作为输入。
以下示例突出了 raw_input 和 input 之间的区别。
>>> a=raw_input("enter your test here : ")
enter your test here : new
>>> a
'new'
>>> print a
new
>>> b=raw_input("enter your python expression :")
enter your python expression : (1,2,3)
>>> print a
new
>>> print b
(1,2,3)
>>> c=input("enter your text here :")
enter your text here :"sunami"
>>> print c
sunami
>>> d=input("enter your text here :")
enter your text here :(1,2,3)
>>> print d
(1, 2, 3)
>>> print type(d)
<type 'tuple'>
>>>e=input("enter your text here :")
enter your text here :[x*x for x in range(5)]
>>> print e
[0, 1, 4, 9, 16]
>>> f=raw_input("enter your python expression :")
enter your python expression :[x*x for x in range(5)]
>>> print f
[x*x for x in range(5)]
>>>
到目前为止,我们一直在输入终端写入,并在终端获得输出。现在让我们进一步了解如何读取和写入文件。Python 提供了大量用于读取和写入文件的函数,这些文件可以是文本文件或数据文件。文件操作命令是通过文件对象完成的。
文件操作函数列表已作为示例突出显示,并在注释中提供了说明。可以打开文件以供读取、写入或追加现有文本。
“open”函数打开一个文件,该文件可用于读取、写入或追加数据。为了执行上述任何功能,必须先打开每个文件。
>>> myfile=open("example.txt", "w")
>>> myfile.write("Oh my god!! I just opened a new file ! \n")
>>> myfile.write("I typed in a whole lot of text \n")
>>> myfile.write("Thank god, its ending ! \n")
>>> myfile.close()
>>>
请记住关闭文件,然后检查实际文件是否包含已写入文件的内容。现在,让我们继续读取刚刚写入的文件的内容。
>>> myfile=open("example.txt", "r")
>>> for a in myfile.readlines():
print a
Oh my god!! I just opened a new file !
I typed in a whole lot of text
Thank god, its ending !
>>>
>>> myfile.close()
>>> myfile=open("example.txt", "w")
>>> myfile.write("Start of a new chapter ! \n")
>>> myfile.write("The second line in charter! \n")
>>> myfile.close()
>>> myfile=open("example.txt", "a")
>>> myfile.write("Oh my god!! I just opened a new file ! \n")
>>> myfile.write("I typed in a whole lot of text \n")
>>> myfile.write("Thank god, its ending ! \n")
>>> myfile.close()
>>> myfile=open("example.txt", "r")
>>> print myfile
<open file 'example.txt', mode 'r' at 0x02115180>
>>> myfile.close()
Python 模块“os”提供用于执行文件处理操作(如重命名和删除文件)的方法。要获取当前工作目录,请执行以下操作。
>>> import os
>>> print os.getcwd()
C:\Users\Desktop\Projects\Upwork
I already have an existing file named example.txt which I will rename using the Python os utility functions.
>>>os.rename("example.txt", "sample.txt")