新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:教你一招!Python讀取文件內容為字符串的方法
方法1:

拷貝文章時,直接把內容賦值給一個變量,保存到一個 .py 文件中。然后在腳本中,導入它。
存儲文章的文件 article.py
content = """ 復制的文章內容 """
存儲腳本的文件 my_code.py
from article import content
方法2:
拷貝文章內容到一個txt文件(通常人們都這么干)。直接讀取文件內容。
用 read() 方法能直接生成字符串。
with open('test.txt','r',encoding='utf-8') as f:
content = f.read()方法3:
用readlines()或readline()結合 for 迭代來自己構成 字符串。
比如 bsdzsz 的代碼片段:
data = ''
with open('test.txt', 'r',encoding='utf-8') as f:
for line in f.readlines():
line = line.strip()
data += line 網(wǎng)站欄目:創(chuàng)新互聯(lián)Python教程:教你一招!Python讀取文件內容為字符串的方法
當前網(wǎng)址:http://www.5511xx.com/article/coephsj.html


咨詢
建站咨詢
