如何在Python中读取文件并将其内容写入具有以下条件的其他文件:
如果字符是输入文件中的字母,则该字母应为小写并写入输出文件。不应写其他字符。
def lower_case():
file_name = input("Enter the file name to read from: ")
tmp_read = open(str(file_name), 'r')
tmp_read.readline()
fileName = input("Enter the file name to write to... ")
tmp_write = open(str(fileName), "w")
for line in tmp_read:
if str(line).isalpha():
tmp_write.write(str(line).lower())
print("Successful!")
if __name__ == "__main__":
lower_case()
答案 0 :(得分:0)
这将检查字符isalpha()或isspace()的天气,然后写入新文件。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def lower_case():
input_name = input("Enter the file name to read from: ")
output_name = input("Enter the file name to write to... ")
with open(str(input_name), 'r') as i:
content = i.readlines()
with open(str(output_name),'wb') as o:
for line in content:
o.write(''.join(c for c in line if c.isalpha() or c.isspace()).lower())
if __name__ == "__main__":
lower_case()
答案 1 :(得分:-1)
<强>代码强>
input_f = input("Enter the file name to read from: ")
output_f = input("Enter the file name to write to... ")
fw = open(output_f, "w")
with open(input_f) as fo:
for w in fo:
for c in w:
if c.isalpha():
fw.write(c.lower())
if c.isspace():
fw.write('\n')
fo.close()
fw.close()
input.txt中
HELLO
12345
WORLD
67890
UTRECHT
030
dafsf434ffewr354tfffff44344fsfsd89087uefwerwe
output.txt的
hello
world
utrecht
dafsfffewrtffffffsfsduefwerwe
<强>来源强>