用python写一个能读取txt文件并修改的代码
时间: 2023-02-15 08:53:37 浏览: 62
。
```
代码如下:
```python
filename = input("请输入文件名:")
with open(filename, "r") as file:
content = file.read()
content = content.replace("旧字符串", "新字符串")
with open(filename, "w") as file:
file.write(content)
print("文件已修改完成!")
```
这段代码实现了读取一个txt文件并修改其中的内容。首先,使用input()函数读入文件名,然后使用with语句打开文件,并使用read()方法读取文件内容。接下来,使用replace()函数替换字符串,最后使用with语句再次打开文件,并使用write()方法写入修改后的内容。
相关问题
写一个替换fasta id的代码 用python 读取txt文件
好的,以下是一个 Python 代码示例,可以读取一个 txt 文件中的内容,将其中的 FASTA ID 替换为指定的新 ID:
```python
def rename_fasta_in_txt(txt_file, id_prefix):
"""
读取 txt 文件中的内容,将其中的 FASTA ID 替换为指定的新 ID。
:param txt_file: txt 文件名
:param id_prefix: 新的 ID 前缀
:return: 无返回值
"""
with open(txt_file, 'r') as f:
content = f.read()
# 将 FASTA ID 替换为新的 ID
new_content = content.replace('\n>', '\n>' + id_prefix)
with open(txt_file, 'w') as f:
f.write(new_content)
```
在调用此函数时,需要提供 txt 文件名和新的 ID 前缀。例如:
```python
txt_file = 'example.txt'
new_prefix = 'new_id_prefix'
rename_fasta_in_txt(txt_file, new_prefix)
```
这将会读取 `example.txt` 文件中的内容,将其中的 FASTA ID 替换为以 `new_id_prefix` 开头的新 ID,并将修改后的内容写回到原文件中。注意:在运行代码前,请确保您的 txt 文件中的 FASTA ID 的格式是以 `>` 开头并紧跟着 ID 的。
用python生成一段代码读取txt文件
可以使用Python内置的`open()`函数来读取txt文件。以下是一个简单的示例代码:
```python
filename = 'example.txt' # 文件名
with open(filename, 'r') as file:
content = file.read() # 读取文件内容
print(content)
```
其中,`filename`变量存储了文件名,`with open(filename, 'r')`语句打开了文件并指定了读取模式(`'r'`)。`file.read()`方法读取了整个文件内容并存储到`content`变量中。最后使用`print()`函数输出了读取到的内容。
需要注意的是,文件路径需要根据实际情况进行修改,如果文件与代码在同一目录下,可以直接使用文件名作为路径;如果文件在其他目录下,需要指定完整的路径。