首页 > 编程知识 正文

Python输入问题的解决方法

时间:2023-11-20 09:33:06 阅读:306805 作者:CFFV

Python是一种简单易学的编程语言,广泛应用于各个领域。在Python中,输入是程序与用户交互的重要方式之一。本文将从多个方面介绍Python输入问题的解决方法。

一、从控制台输入

1、使用input()函数

name = input("请输入您的姓名:")
print("您好," + name)

2、使用sys模块的stdin

import sys
name = sys.stdin.readline().rstrip()
print("您好," + name)

3、使用argparse模块解析命令行参数

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name", help="请输入您的姓名")
args = parser.parse_args()
print("您好," + args.name)

二、从文件输入

1、使用open()函数读取文件内容

with open("input.txt", "r") as file:
    content = file.read()
    print(content)

2、使用pandas库读取CSV文件

import pandas as pd
data = pd.read_csv("input.csv")
print(data)

3、使用xlrd库读取Excel文件

import xlrd
data = xlrd.open_workbook("input.xlsx")
sheet = data.sheet_by_index(0)
print(sheet.cell_value(0, 0))

三、从网络输入

1、使用requests库发送HTTP请求获取数据

import requests
response = requests.get("http://example.com")
print(response.text)

2、使用urllib库发送HTTP请求获取数据

import urllib.request
response = urllib.request.urlopen("http://example.com")
content = response.read().decode("utf-8")
print(content)

3、使用scrapy库爬取网页数据

import scrapy

class ExampleSpider(scrapy.Spider):
    name = "example"
    
    def start_requests(self):
        yield scrapy.Request(url="http://example.com", callback=self.parse)
    
    def parse(self, response):
        print(response.text)

四、从命令行参数输入

1、使用sys模块的argv

import sys
name = sys.argv[1]
print("您好," + name)

2、使用argparse模块解析命令行参数

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name", help="请输入您的姓名")
args = parser.parse_args()
print("您好," + args.name)

3、使用getopt模块解析命令行选项

import getopt
import sys

opts, args = getopt.getopt(sys.argv[1:], "hn:", ["help", "name="])
for opt, arg in opts:
    if opt in ("-h", "--help"):
        print("Usage: python example.py -n ")
    elif opt in ("-n", "--name"):
        name = arg

print("您好," + name)

五、从数据库输入

1、使用MySQLdb库连接MySQL数据库

import MySQLdb

conn = MySQLdb.connect(host="localhost", user="root", passwd="password", db="example")
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
print(result)

2、使用pymongo库连接MongoDB数据库

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["example"]
collection = db["users"]
result = collection.find()
for document in result:
    print(document)

3、使用sqlite3库连接SQLite数据库

import sqlite3

conn = sqlite3.connect("example.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
print(result)

以上是Python输入问题的解决方法,希望对您有所帮助!

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。