python修改文本并获取修改时间并显示在文本中
时间: 2024-05-05 22:20:06 浏览: 10
您可以使用Python中的os和datetime模块来实现此功能。首先,您需要通过使用open()函数将要修改的文本文件打开并读取其中的内容。然后,您可以使用replace()函数将文本中的任何内容进行替换。接下来,您可以使用datetime模块的now()函数获取当前时间,并将其转换为所需的日期和时间格式。最后,您可以将修改后的内容和日期时间写回到原始文本文件中。
以下是一个示例代码,用于修改文本并获取修改时间并显示在文本中:
```
import os
from datetime import datetime
# Open the file
with open('example.txt', 'r') as file:
data = file.read()
# Replace a string in the file
new_data = data.replace('old string', 'new string')
# Get the current date and time
now = datetime.now()
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
# Write the modified text and date/time back to the file
with open('example.txt', 'w') as file:
file.write(new_data)
file.write('\n\nLast modified: {}'.format(date_time))
# Close the file
file.close()
```
请注意,在此示例代码中,我们假设要修改的文件名为'example.txt',并且我们将字符串'old string'替换为'new string'。您可以根据需要修改这些值。
相关推荐
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)