Python3 输入和输出
Python3 输入和输出
在Python中,输入输出是非常重要的概念。本篇文章将介绍Python3中的输入和输出。
输出
在Python中,输出通常使用print()
函数。下面是一个简单的例子:
print("Hello, World!")
输出:
Hello, World!
print()
可以同时输出多个变量。这些变量之间默认用空格分隔。
name = "Alice"
age = 25
print("My name is", name, "and I'm", age, "years old.")
输出:
My name is Alice and I'm 25 years old.
如果想要将变量之间用其他字符隔开,可以使用sep
参数。
name = "Alice"
age = 25
print("My name is", name, "and I'm", age, "years old.", sep="-")
输出:
My name is-Alice-and I'm-25-years old.
如果想要在输出的末尾添加一个换行符,可以使用end
参数。
print("Hello")
print("World")
输出:
Hello
World
print("Hello", end="\n")
print("World", end="\n")
输出:
Hello
World
print("Hello", end=" ")
print("World", end="\n")
输出:
Hello World
输入
在Python中,输入通常使用input()
函数。input()
函数将用户输入的字符串返回给程序。
name = input("What is your name? ")
print("Hello,", name)
输出:
What is your name? Alice
Hello, Alice
注意,input()
函数返回一个字符串。如果需要将字符串转换为其他类型,可以使用类型转换函数。例如:
age = int(input("What is your age? "))
print("You will be 5 years older in", age+5, "years.")
输出:
What is your age? 25
You will be 5 years older in 30 years.
文件操作
Python也提供了读写文件的功能。
文件打开和关闭
使用open()
函数打开文件,函数返回一个文件对象。
file = open("test.txt", "r")
函数有两个参数,第一个参数是文件名,第二个参数是打开文件的模式:
r
:只读模式。w
:写入模式。如果文件已经存在,会截断文件。如果文件不存在,会创建一个新文件。a
:追加模式。如果文件已经存在,会在文件结尾追加新内容。如果文件不存在,会创建一个新文件。x
:独占写入模式。仅在文件不存在时创建新文件。
文件读写完成后,需要使用close()
函数关闭文件。
file.close()
文件写入
使用write()
函数写入文件。
file = open("test.txt", "w")
file.write("Hello, World!")
file.close()
文件读取
使用read()
函数读取文件。
file = open("test.txt", "r")
print(file.read())
file.close()
也可以一行一行地读取文件。
file = open("test.txt", "r")
for line in file:
print(line.strip()) # strip()函数去掉行末的换行符
file.close()
with语句自动关闭文件
使用with
语句可以自动关闭文件。
with open("test.txt", "r") as file:
print(file.read())
结论
本文介绍了Python3中的输入和输出,以及文件操作的基本用法。这些基本操作是Python编程中的重要组成部分,尤其是在处理文本数据方面。