将文本文件读入 Python
打开文档并加载其内容
将文本文件读入 Python 是 CoddyKit 上的免费 NLP Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 NLP Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 NLP Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Real Text Lives in Files
Most NLP work starts with documents stored on disk. Your first job is to load that text from a file into a Python string. 📄
Open a File With open
The open function connects Python to a file. You give it a path and a mode like r, which means read.
f = open("notes.txt", "r")
text = f.read()
f.close()Read the Whole File
The read method pulls the entire file into one string. That is handy for small documents you want to process all at once.
content = f.read()
print(len(content)) # total charactersAlways Close What You Open
An open file holds a system resource. Forgetting to close it can lose data or leak handles, so closing matters.
The with Statement Is Safer
A with block opens the file and closes it automatically when you are done, even if an error happens partway through.
with open("notes.txt", "r") as f:
text = f.read()Always Set the Encoding
Pass encoding so Python decodes bytes correctly. Using utf-8 explicitly avoids surprises across different machines.
with open("notes.txt", encoding="utf-8") as f:
text = f.read()Read Line by Line
Looping over the file object yields one line at a time. This is gentle on memory for very large documents.
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())Get All Lines as a List
The readlines method returns every line as a list of strings, which is useful when you want to index or count lines.
lines = f.readlines()
print(len(lines)) # number of linesLines Keep Their Newline
Each read line ends with a hidden newline character. Call strip to remove that trailing whitespace before processing.
clean = line.strip()Handle Missing Files
If the path is wrong, Python raises a FileNotFoundError. Wrap risky reads in try and except to fail gracefully.
try:
open("missing.txt")
except FileNotFoundError:
print("No such file")Paths Matter
A relative path is read from where you run the script. When in doubt, use a full path so Python finds the right file.
Quick Check
Think about why one way of opening files is preferred.
Recap: Loading Text Safely
You learned to open files with a with block, set utf-8 encoding, read whole text or line by line, and handle missing files. 📥
常见问题解答
「将文本文件读入 Python」课时是免费的吗?
是的 — 「将文本文件读入 Python」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NLP Academy 课程的其余内容,请升级到 CoddyKit PRO。 NLP Academy 课程共包含 4 节课。
「将文本文件读入 Python」这节课中我会学到什么?
打开文档并加载其内容 你通过在浏览器中直接运行的动手代码来练习 NLP Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 NLP Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 NLP Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「将文本文件读入 Python」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 NLP Academy 课中编写并运行代码吗?
能。每节 NLP Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。