如何在使用 readlines() 读取文件行后避免自动换行并实现同一行输出

20次阅读

如何在使用 readlines() 读取文件行后避免自动换行并实现同一行输出

使用 `readlines()` 读取的每一行末尾默认包含换行符 `n`,导致拼接字符串时内容被强制换行;只需调用 `.strip()` 去除首尾空白(含换行符),即可实现预期的单行输出。

当你通过 open(‘wordlist.txt’).readlines() 读取文件时,python 会将每行内容(包括结尾的 n)完整保留。因此,即使你只是随机选中一行并尝试与另一字符串拼接,该隐式换行符仍会生效:

import random  random_line = random.choice(open('wordlist.txt').readlines()) print(random_line + "This does not appear on same line")

输出为:

f2kd This does not appear on same line

这是因为 random_line 实际值是 “f2kdn”,而非 “f2kd”。

✅ 正确做法是使用 .strip() 清除行尾换行符(同时也可去除首尾空格、制表符等):

import random  with open('wordlist.txt') as f:     random_line = random.choice(f.readlines()).strip() print(random_line + "This appears on the same line")

⚠️ 注意:推荐使用 with open(…) 语句替代裸 open(),确保文件正确关闭,避免资源泄漏。

此外,.strip() 比 .rstrip(‘n’) 更健壮——它能处理 windows(rn)、macOS(r)和 unix(n)等不同平台的行尾格式,且兼容前后多余空格。若需保留前导/尾随空格仅删换行符,才考虑 .rstrip(‘n’)。

? 小技巧:也可直接用 read().splitlines() 替代 readlines(),它默认不带换行符:

lines = open('wordlist.txt').read().splitlines() random_line = random.choice(lines) print(random_line + "This also works on same line")

综上,.strip() 是最简洁、跨平台、安全的解决方案。

text=ZqhQzanResources