【Python】【问题排查】readlines()逐行读取文件后writelinees()逐行输出,少了一行

本文最后更新于:2024年5月18日 晚上 18:37

【Python】【问题排查】readlines()逐行读取文件后writelinees()逐行输出,少了一行

问题代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import os
import sys
import time

def sort():
name = input("Please enter the name of the file: ")
file_encoding = "utf-8"
try:
with open(os.path.join(sys.path[0], name + ".txt"), "r", encoding=file_encoding) as f:
data = f.readlines()
except FileNotFoundError:
print("The file does not exist.")
return
except UnicodeDecodeError:
file_encoding="gbk"
with open(os.path.join(sys.path[0], name + ".txt"), "r", encoding="gbk") as f:
data = f.readlines()
except:
print("The file cannot be read.")
return
# 对数据进行排序
data.sort()
with open(os.path.join(sys.path[0], name + "_sorted.txt"), "w", encoding=file_encoding) as f:
f.writelines(data)
print("The data has been sorted successfully.")

if __name__ == "__main__":
sort()
time.sleep(2)

脚本代码会从名为"data.txt"的文件中读取数据,使用readlines()读取文件。然后根据字典顺序,按升序对数据进行排序。每行数据视为一个数据项。然后将排序后的结果使用writelines(),存储在名为"data_sorted.txt"的文件中。

支持UTF-8编码,并且在读取文件时会处理可能出现的编码异常。执行脚本后,会将数据排序并输出成功消息。

问题原因

当你使用readlines()方法读取文件时,它会将文件内容按行读取,并返回一个包含每行数据的列表。每行数据都会保留原来的换行符。例如,如果文件内容如下:

1
2
3
Line 1
Line 2
Line 3

使用readlines()方法读取后,返回的列表如下:

1
['Line 1\n', 'Line 2\n', 'Line 3\n']

注意,每个列表元素都保留了原来的换行符。

然后,在使用writelines()方法将数据写入文件时,它会接受一个包含字符串的可迭代对象(例如,列表),并将每个字符串写入文件。但是,writelines()方法不会自动添加换行符。它只是简单地将每个字符串写入文件,不对字符串进行任何修改。

因此,如果原始文件的最后一行没有换行符,那么在使用writelines()方法写入文件时,该行的数据就会与下一行的数据连在一起,导致缺少一行数据。

为了确保每行数据都包含换行符,你可以使用read()方法读取整个文件的内容,然后使用splitlines()方法将内容按行分割成列表。这样,每行数据都会保留换行符。

例如,对于上面的示例文件内容:

1
2
with open(os.path.join(sys.path[0], name + ".txt"), "r", encoding=file_encoding) as f:
data = f.read().splitlines()

此时,data列表将如下所示:

1
['Line 1', 'Line 2', 'Line 3']

可以看到,每行数据不再包含换行符。

在写入文件时,你可以使用join()方法将每行数据拼接成一个字符串,并使用换行符连接它们,然后将这个字符串写入文件。

1
2
with open(os.path.join(sys.path[0], name + "_sorted.txt"), "w", encoding=file_encoding) as f:
f.write('\n'.join(data))

这样,每行数据都会以换行符作为分隔符写入文件,确保排序后的文件包含所有原始数据行。

——回答来自与ChatGPT 3.5的对话


【Python】【问题排查】readlines()逐行读取文件后writelinees()逐行输出,少了一行
https://qalxry.github.io/2023/06/12/【Python】【问题排查】readlines-逐行读取文件后writelinees-逐行输出,少了一行/
作者
しずり雪
发布于
2023年6月12日
更新于
2024年5月18日
许可协议