Python输入,输出,Python导入
在本教程中,我们将介绍Python输入/输出的基础知识,以及如何在python程序中导入模块。
先前我们了解了Python数据类型。
您可以从Python数据类型中学到这一点。
Python输入输出
I/O表示输入和输出。
我们将学习python输入和输出的基本功能。
将输出打印到屏幕
我们已经熟悉print()
函数。
它用于将某些内容打印到屏幕上。
print("Print something to the screen")
此外,我们可以在打印函数中传递两个或者多个不同的字符串,并用逗号(,)或者加号(+)分隔。
像这样;
print("This is first String " + "Followed by this string"); #Or can be written like this also print("This is another String " , "Followed by another string");
接受用户输入
有时我们的程序可能需要读取用户提供的键盘输入。
因此,我们将使用input()
函数。
" input()"函数从标准输入读取一行。
换句话说,输入功能将从键盘输入中读取内容,直到给出换行符为止(即,按Enter键)。
#takes input from keyboard and stores in a string str = input("Enter your input: "); #then we can print the string print(str)
如果您运行此程序,则会在下图看到如下提示,等待您进行输入。
直到按Enter为止,它将占用您输入的尽可能多的字符。
Python I/O –文件操作
有时我们需要从文件读取和写入。
因此,有些功能可用。
打开文件
为了打开文件,我们使用open()函数。
这是Python中的内置函数。
f = open("input_file.txt") # open "input_file.txt" file in current directory f = open("C:/Python34/README.txt") # specifying full path of a file
您还可以指定打开该文件的模式或者目的。
f = open("input_file.txt",'r') # open "input_file.txt" file to read purpose f = open("input_file",'w') # open "input_file.txt" file to write purpose f = open("input_file",'a') # open "input_file.txt" file to append purpose
文件关闭
处理完文件后,需要关闭它。
为此,我们将使用close()函数。
f = open("input_file.txt") # open "input_file.txt" file #do file operation. f.close()
从文件读取
为了读取文件,有几个功能。
在下面的程序中,我们将探索这些功能。
您可以使用
read()
函数从文件中读取一定数量的字节。您可以使用
readline()
函数逐行读取文件。您还可以一次读取所有行,并将这些行存储在字符串列表中。
写入文件
将某些内容写入文件非常简单,类似于读取文件。
我们将使用write()
函数。
f = open("input.txt") # open "input.txt" file str=f.read(10) #read first 10 bytes from the file. print(str) #print first 10 bytes from the file. f.close()
Python导入
每当我们想在Python程序中使用包或者模块时,首先我们需要使其可访问。
因此,我们需要在程序中导入该包或者模块。
假设我们有一个数字。
我们要打印它的平方根。
因此,如果我们在下面编写此程序,则它应该可以正常工作。
f = open("input.txt") # open "input.txt" file str=f.readline() #read first line from the file. print(str) #print the first line. str=f.readline() #read second line from the file. print(str) #print the second line. f.close()
但是,如果我们运行该程序,它将显示如下错误:
这是因为sqrt()
函数位于模块名称" math"下。
因此,如果要使用此功能,我们需要通过导入"数学"模块使此模块可访问。
因此正确的代码将如下所示
f = open("input.txt") # open "input.txt" file str=f.readlines() #read all the lines from the file at once. and store as a list of string print(str) #print list of all the lines. f.close()