with open(r'D:\1.txt', 'r') as src, open(r'D:2.txt', 'w') as dst: for line in src: dst.write(line.swapcase())
时间: 2024-01-24 09:02:38 浏览: 28
这段代码将打开文件 `D:\1.txt`,并将其内容逐行读取,然后将每行中的所有字母大小写互换,并将结果写入到文件 `D:\2.txt` 中。具体来说,`open(r'D:\1.txt', 'r')` 打开文件 `D:\1.txt` 并以只读模式读取它,`open(r'D:\2.txt', 'w')` 打开文件 `D:\2.txt` 并以只写模式打开它。`for line in src` 循环读取 `src` 中的每一行,`line.swapcase()` 将每行中的所有字母大小写互换,`dst.write(line.swapcase())` 将处理后的结果写入到文件 `D:\2.txt` 中。最后,代码块结束,两个文件会自动关闭。
相关问题
功能描述:已知当前文件夹中有纯英文文本文件readme.txt,把readme.txt文件中的所有内容复制到dst.txt中, with open('readme.txt','r') as src, open('dst.txt', __________) as dst: dst.write(src.read())
可以使用 `'w'` 模式打开 `dst.txt` 文件进行写入,完整的代码如下:
```
with open('readme.txt', 'r') as src, open('dst.txt', 'w') as dst:
dst.write(src.read())
```
其中,`'r'` 模式表示以只读方式打开 `readme.txt` 文件,`'w'` 模式表示以写方式打开 `dst.txt` 文件。在 `with` 语句块中,读取 `readme.txt` 文件的全部内容,并将其写入到 `dst.txt` 文件中。注意,如果 `dst.txt` 文件不存在,则会自动创建。
代碼報錯,請修改import os import shutil from datetime import date src_folder = r"Y:\iplas\Robot_Log\SMT" dst_folder = "D:\測試log" today = date.today() for file_name in os.listdir(src_folder): if file_name.endswith('.txt'): file_path = os.path.join(src_folder, file_name) if date.fromtimestamp(os.path.getmtime(file_path)) == today: shutil.copy(file_path, os.path.join(dst_folder, f"{file_name},{file_name}")) file_contents = [] for file_name in os.listdir(dst_folder): if file_name.endswith('.txt'): with open(os.path.join(dst_folder, file_name), 'r', encoding='gbk') as t: file_content = t.read().strip() file_contents.append(f"{file_content},{file_name}") with open(os.path.join(dst_folder, '汇总文档.txt'), 'w', encoding='gbk') as f: f.write('\n\n'.join(file_contents))
请尝试使用以下代码,它会在文件名中添加当天日期,并且在复制文件时会创建目标文件夹(如果不存在),还会在文件读取时处理异常情况:
```
import os
import shutil
from datetime import date
src_folder = r"Y:\iplas\Robot_Log\SMT"
dst_folder = r"D:\測試log"
today = date.today()
# create target folder if it does not exist
if not os.path.exists(dst_folder):
os.makedirs(dst_folder)
for file_name in os.listdir(src_folder):
if file_name.endswith('.txt'):
file_path = os.path.join(src_folder, file_name)
if date.fromtimestamp(os.path.getmtime(file_path)) == today:
new_file_name = f"{file_name[:-4]}_{today.strftime('%Y%m%d')}.txt"
shutil.copy(file_path, os.path.join(dst_folder, new_file_name))
file_contents = []
for file_name in os.listdir(dst_folder):
if file_name.endswith('.txt'):
try:
with open(os.path.join(dst_folder, file_name), 'r', encoding='gbk') as t:
file_content = t.read().strip()
file_contents.append(f"{file_content},{file_name}")
except Exception as e:
print(f"Error reading file {file_name}: {e}")
with open(os.path.join(dst_folder, '汇总文档.txt'), 'w', encoding='gbk') as f:
f.write('\n\n'.join(file_contents))
```