python练习题(二)

发布时间 2023-10-09 20:53:57作者: 马文涛测试开发

文件操作

1.读取一个文本文件,打印文件内容到控制台。

def print_file_content(file_path):
    try:
        with open(file_path, 'r') as file:
            content = file.read()
            print(content)
    except Exception as e:
        print(f"没有找到文件:{e}")


# 读取并打印文件内容
file_path = '1.txt'
print_file_content(file_path)

2.从一个文本文件中读取每行内容,将其存储为列表。

file_path = '1.txt'  # 请替换为你的文件路径
lines_list = []

try:
    with open(file_path, 'r') as file:
        lines_list = file.readlines()
except FileNotFoundError:
    print(f"File '{file_path}' not found.")

# 打印读取到的每行内容列表
print(lines_list)

3.从一个文本文件中读取每行内容,统计文件中的单词数目。

def count_words(file_path):
    word_count = 0
    try:
        with open(file_path, 'r') as file:
            for line in file:
                # 使用空格拆分每行为单词
                words = line.split()
                word_count += len(words)
    except Exception as e:
        print(f"出错啦:{e}")
    return word_count


# 统计单词数
file_path = '1.txt'
total_words = count_words(file_path)
print(f'这个文件有: {total_words} 个单词')

4.写一个程序,接受用户输入并将其写入一个新文件。

def write_user_input_to_file(file_path):
    try:
        # 接受用户输入
        user_input = input("给文件写入内容: ")

        # 写入用户输入到文件
        with open(file_path, 'w') as file:
            file.write(user_input)
        print("输入内容已经写入成功")
    except Exception as e:
        print(f"写入失败{e}")


# 获取要写入的文件路径
file_path = '1.txt'

# 调用函数将用户输入写入文件
write_user_input_to_file(file_path)

 

5.追加一些文本到已有文件的末尾。

def append_text_to_file(file_path, text_to_append):
    """
    :param file_path:
    :param text_to_append:
    :return:
    """
    try:
        # 打开文件以追加模式
        with open(file_path, 'a') as file:
            # 追加文本到文件末尾
            file.write(text_to_append + '\n')
        print("文件追加完成")
    except Exception as e:
        print(f"An error occurred: {str(e)}")


# 获取要追加的文件路径和文本
file_path = '1.txt'
text_to_append = "您好"

# 调用函数追加文本到文件
append_text_to_file(file_path, text_to_append)

6.追加当前日期和时间到日志文件

import datetime


def append_datetime_to_log(file_path):
    """
    :param file_path: 
    :return: 
    """
    try:
        # 获取当前日期和时间
        current_datetime = datetime.datetime.now()
        formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")

        # 打开文件以追加模式
        with open(file_path, 'a') as file:
            # 追加日期和时间到文件末尾
            file.write("Current datetime: " + formatted_datetime + '\n')
        print("Datetime appended to the log.")
    except Exception as e:
        print(f"报错了:{e}")


# 获取要追加的日志文件路径
log_file_path = '1.txt'  # 请替换为你的日志文件路径

# 调用函数追加当前日期和时间到日志文件
append_datetime_to_log(log_file_path)

7.重命名一个文件为指定的新文件名。

import os


def rename_file(old_file_path, new_file_name):
    """
    :param old_file_path: 
    :param new_file_name: 
    :return: 
    """
    try:
        # 从旧文件路径中获取文件所在目录
        directory = os.path.dirname(old_file_path)

        # 构建新文件的完整路径
        new_file_path = os.path.join(directory, new_file_name)

        # 重命名文件
        os.rename(old_file_path, new_file_path)
        print(f"修改文件名: {new_file_path} 成功!")
    except Exception as e:
        print(f"出错了: {e}")


# 获取要重命名的文件路径和新文件名
old_file_path = '1.txt'
new_file_name = 'new_filename.txt'

# 调用函数重命名文件
rename_file(old_file_path, new_file_name)

8.根据用户输入的新文件名,重命名一个文件。

import os


def rename_file(old_file_path, new_file_name):
    """
    :param old_file_path:
    :param new_file_name:
    :return:
    """
    try:
        # 从旧文件路径中获取文件所在目录
        directory = os.path.dirname(old_file_path)

        # 新文件的完整路径
        new_file_path = os.path.join(directory, new_file_name)

        # 重命名文件
        os.rename(old_file_path, new_file_path)
        print(f"文件命名为: {new_file_path} 成功!")
    except Exception as e:
        print(f"出错啦: {e}")


# 获取要重命名的文件路径
old_file_path = 'new_filename.txt'

# 获取用户输入的新文件名
new_file_name = input("输入新的文件名称: ")

# 调用函数重命名文件
rename_file(old_file_path, new_file_name)

9.删除一个指定的文件。

import os


def delete_file(file_path):
    """
    :param file_path:
    :return: 
    """
    try:
        # 删除指定文件
        os.remove(file_path)
        print(f"文件 '{file_path}' 已经删除成功!")
    except Exception as e:
        print(f"An error occurred: {str(e)}")


# 获取要删除的文件路径
file_to_delete = 'example.txt'

# 调用函数删除文件
delete_file(file_to_delete)

10.删除文件夹中所有文件。

 

import os


def delete_all_files_in_folder(folder_path):
    """
    :param folder_path:
    :return:
    """
    try:
        # 获取文件夹中所有文件
        files = os.listdir(folder_path)

        # 遍历并删除所有文件
        for file in files:
            file_path = os.path.join(folder_path, file)
            os.remove(file_path)
            print(f"文件'{file}'已经删除成功!")

        print("所有文件删除成功!")
    except Exception as e:
        print(f"出错啦: {e}")


# 获取要删除文件的文件夹路径
folder_path = 'demo'

# 调用函数删除文件夹中的所有文件
delete_all_files_in_folder(folder_path)

11.处理文件不存在的情况,给出友好的错误提示信息。

import os


def delete_file(file_path):
    """
    :param file_path:
    :return:
    """
    try:
        # 检查文件是否存在
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"文件'{file_path}'没有找到!")

        # 删除指定文件
        os.remove(file_path)
        print(f"文件'{file_path}'已经被删除!")
    except Exception as e:
        print(f"出错了: {e}")


# 获取要删除的文件路径
file_to_delete = '1.txt'

# 调用函数删除文件
delete_file(file_to_delete)

12.检查文件是否存在,如果存在则删除它。

import os


def delete_file_if_exists(file_path):
    try:
        # 检查文件是否存在
        if os.path.exists(file_path):
            os.remove(file_path)
            print(f"文件'{file_path}'已经被删除")
        else:
            print(f"文件'{file_path}'不存在!")
    except Exception as e:
        print(f"出错了: {e}")


# 获取要删除的文件路径
file_to_delete = '1.txt'

# 调用函数删除文件(如果存在)
delete_file_if_exists(file_to_delete)

13.复制一个文件到另一个位置(备份)

def copy_file_without_shutil(source_file, destination_file):
    try:
        # 打开源文件进行读取
        with open(source_file, 'rb') as source:
            # 打开目标文件进行写入
            with open(destination_file, 'wb') as destination:
                # 逐块读取源文件并写入到目标文件
                while True:
                    chunk = source.read(1024)  # 读取 1KB 的数据
                    if not chunk:
                        break
                    destination.write(chunk)

        print(f"文件'{source_file}'已经复制成 '{destination_file}'.")
    except Exception as e:
        print(f"出错了: {e}")


# 源文件路径和目标文件路径
source_file_path = 'x.txt'
destination_file_path = 'y.txt'

# 调用函数复制文件
copy_file_without_shutil(source_file_path, destination_file_path)

14.将两个文件合并为一个新文件。

def merge_files(file1_path, file2_path, merged_file_path):
    """
    :param file1_path:
    :param file2_path:
    :param merged_file_path:
    :return:
    """
    try:
        with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2:
            # 读取第一个文件内容
            file1_content = file1.read()

            # 读取第二个文件内容
            file2_content = file2.read()

            # 合并内容
            merged_content = file1_content + '\n' + file2_content

            # 写入到新文件
            with open(merged_file_path, 'w') as merged_file:
                merged_file.write(merged_content)

        print(f"文件 '{file1_path}' 和 '{file2_path}' 合并为 '{merged_file_path}'成功!")
    except Exception as e:
        print(f"出错了: {e}")


# 文件1路径和文件2路径
file1_path = '1.txt'
file2_path = '2.txt'

# 合并后的新文件路径
merged_file_path = '3.txt'

# 合并文件
merge_files(file1_path, file2_path, merged_file_path)