篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python操作txt文件中数据教程[1]-使用python读写txt文件相关的知识,希望对你有一定的参考价值。
python操作txt文件中数据教程[1]-使用python读写txt文件
觉得有用的话,欢迎一起讨论相互学习~
- 原始txt文件
- 程序实现后结果
程序实现
filename = \'./test/test.txt\'
contents = []
DNA_sequence = []
# 打开文本并将所有内容存入contents中
with open(filename, \'r\') as f:
for line in f.readlines():
contents.append(line)
f.close()
# 对contents中的内容进行遍历
# 并将需要的数据存到list DNA_sequence中
for content in contents: # 逐行遍历
p = 0 #
for bit in content: # 对每行进行逐字遍历
if bit == " ": # 遇到空格时进行处理
DNA_sequence.append(content[0:p]) # 将content中的0:p字段存入新列表new中,用于写入新的.txt中
break # 处理完一行以后跳出当前循环
else:
p = p + 1 # 如果bit不是空格,指针加1
# print(DNA_sequence)
"""
[\'AAACAAGGAACAAACGCACA\', \'AAAGGACACAGTGAGAGACG\', \'AGCCATTGTCGAGTCCGTTA\', \'GTGGTCACTCCTCGCAAATT\', \'TTCAACCATACAGGCCTCGT\',
\'CAAATGTGAGGATTCGGACG\', \'CCGTGGTGAACTGGAGCGTT\', \'Sum\', \'AAAGGACACAGTGAGAGACG\', \'AGCCATTGTCGAGTCCGTTA\',
\'CCACAACGCTCGAAGGCAAG\', \'AAGTACAGCGGGCCAATAGC\', \'CAAATGTGAGGATTCGGACG\', \'GAGAACGTTGAGTGAGCGTG\', \'GATGTTAAGTAGAGCAGAGG\',
\'Sum\', \'AAACAAGGAACAAACGCACA\', \'AAAGGACACAGTGAGAGACG\', \'CCACAACGCTCGAAGGCAAG\', \'AAGTACAGCGGGCCAAGATC\',
\'CTCAGAAGATCTCGATGGCT\', \'AGCCATTGTCGAGTCCGTTA\', \'TGCCGCAAACTACACACACG\', \'Sum\']
"""
# 由于list DNA_sequence中有不需要的字符串"Sum",将其从列表中去除
for var in DNA_sequence:
if var == "Sum":
DNA_sequence.remove(var)
# print(DNA_sequence)
"""
[\'AAACAAGGAACAAACGCACA\', \'AAAGGACACAGTGAGAGACG\', \'AGCCATTGTCGAGTCCGTTA\', \'GTGGTCACTCCTCGCAAATT\', \'TTCAACCATACAGGCCTCGT\',
\'CAAATGTGAGGATTCGGACG\', \'CCGTGGTGAACTGGAGCGTT\', \'AAAGGACACAGTGAGAGACG\', \'AGCCATTGTCGAGTCCGTTA\', \'CCACAACGCTCGAAGGCAAG\',
\'AAGTACAGCGGGCCAATAGC\', \'CAAATGTGAGGATTCGGACG\', \'GAGAACGTTGAGTGAGCGTG\', \'GATGTTAAGTAGAGCAGAGG\', \'AAACAAGGAACAAACGCACA\'
, \'AAAGGACACAGTGAGAGACG\', \'CCACAACGCTCGAAGGCAAG\', \'AAGTACAGCGGGCCAAGATC\', \'CTCAGAAGATCTCGATGGCT\',
\'AGCCATTGTCGAGTCCGTTA\', \'TGCCGCAAACTACACACACG\']
"""
# 以写的方式打开文件,如果文件不存在,就会自动创建,如果存在就会覆盖原文件
file_write_obj = open("./DNAlog.txt", \'w\')
# 将DNA_sequence中的数据写入到DNAlog.txt文件中
for var in DNA_sequence:
file_write_obj.writelines(var)
file_write_obj.writelines(\'\\n\')
file_write_obj.close()