with open("text2.txt","r",encoding="utf-8") as f1: newLines = (line.strip() for line in f1) with open("text.txt.bak","w",encoding="utf-8") as f2: for line in newLines: if line.split(",")[4] =="正式": print(line) f2.write(line+"\n")
时间: 2023-11-07 18:54:03 浏览: 39
这段代码的作用是从文件"text2.txt"中读取每一行,然后将符合条件的行写入到文件"text.txt.bak"中。具体地,该代码会打开文件"text2.txt",将每一行去掉收尾空格后生成一个生成器对象newLines。然后,代码打开文件"text.txt.bak",并逐行遍历newLines中的每一行。对于每一行,如果该行的第5个字段(以","为分隔符)为"正式",则将其输出到控制台并写入到文件"text.txt.bak"中。最后,代码关闭了文件句柄。
相关问题
with open('data.csv', 'w', encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerows(rows)
This code snippet opens a file named "data.csv" in write mode with UTF-8 encoding and no newlines. It then creates a CSV writer object and writes the list of rows to the file using the writerows() method. Each row in the list is written as a separate line in the CSV file, with each value separated by a comma. This code is useful for saving data in a CSV format that can be easily read by spreadsheet applications or other programs.
f = open("drawData.csv", mode='w', encoding='utf-8', newline='')
This line of code opens a file called "drawData.csv" in write mode ('w'), using the UTF-8 encoding to handle special characters, and with the newline parameter set to an empty string to prevent extra newlines from being added to the file. The file object is stored in the variable 'f'.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)