【问题描述】文件读写练习(请复习“文件的读写与遍历”一节的内容,并完成下列程序)。现在有一个文本文件novel.txt,用python打开这个文件并遍历文件的每一行,要求只将长度大于50的行写入新文件中,新文件在磁盘上命名为new_novel.txt。
【输入文件】输入文件为当前目录下的 novel.txt。其内容由任意文本构成。
【输出文件】输出文件为当前目录下的 new_novel.txt。
【样例输入】若输入novel.txt文件内容如下:
"Tell us your name!" said the man. "Quick!"
"Pip, sir."
"Once more," said the man, staring at me. "Give it mouth!"
"Pip. Pip, sir."
"Show us where you live," said the man. "Pint out the place!"
I pointed to where our village lay, on the flat in-shore among the
alder-trees and pollards, a mile or more from the church.
【样例输出】输出文件new_novel.txt内容为:
"Once more," said the man, staring at me. "Give it mouth!"
"Show us where you live," said the man. "Pint out the place!"
I pointed to where our village lay, on the flat in-shore among the
alder-trees and pollards, a mile or more from the church.
【样例说明】输入文件为当前目录(即与你编写的python程序同一目录)下的novel.txt,输出文件为当前目录下的new_novel.txt。
根目录创建文件
class Solution:
def __init__(self):
pass
def read_data(self, file_path: str) -> list:
"""
:param file_path:
:return:
"""
with open(file_path, 'r', encoding='utf-8') as f:
content = f.readlines()
return content
def save_data(self, target_path: str, data_array: list) -> None:
"""
:param target_path:
:param data_array:
:return:
"""
with open(target_path, 'w') as f:
for i in data_array:
if len(i) > 50:
f.write(i)
if __name__ == '__main__':
U = Solution()
data = U.read_data(file_path="novel.txt")
U.save_data(target_path="new_novel.txt", data_array=data)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
with open("novel.txt", "r") as fText:
lText = fText.readlines()
lNew = [i for i in lText if len(i) > 50]
with open("new_novel.txt", "w") as fText:
fText.write("".join(lNew))
这是我的答案 望采纳
with open('novel.txt','r') as f:
p = f.readlines()
new = [i for i in p if len(i)>50]
with open('new_novel.txt','w') as f:
f.write(''.join(new))
class Solution:
def __init__(self):
pass
def read_data(self, file_path: str) -> list:
"""
:param file_path:
:return:
"""
with open(file_path, 'r', encoding='utf-8') as f:
content = f.readlines()
return content
def save_data(self, target_path: str, data_array: list) -> None:
"""
:param target_path:
:param data_array:
:return:
"""
with open(target_path, 'w') as f:
for i in data_array:
if len(i) > 50:
f.write(i)
if __name__ == '__main__':
U = Solution()
data = U.read_data(file_path="./novel.txt")
U.save_data(target_path="./new_novel.txt", data_array=data)
手动输入文件的路径和输出路径,对应目标文件路径,和生成文件的路径
1.用open()方法读取文件
基本格式:open(要读取的文件名,读取的模式)
2.python文件读取模式有哪些?
最常见的文件模式有三种:读(r)、写(w)和追加(a)。以下为各种模式以及对应的描述用法:
用Python读写文件的方法
https://blog.csdn.net/pythonandaiot/article/details/121960051