簡體   English   中英

將txt文件導入python

[英]importing txt files into python

a01:01-24-2011:s1 
a03:01-24-2011:s2 
a02:01-24-2011:s2 
a03:02-02-2011:s2 
a03:03-02-2011:s1 
a02:04-19-2011:s2 
a01:05-14-2011:s2 
a02:06-11-2011:s2 
a03:07-12-2011:s1 
a01:08-19-2011:s1 
a03:09-19-2011:s1 
a03:10-19-2011:s2 
a03:11-19-2011:s1 
a03:12-19-2011:s2 

這保存在animallog1.txt 中。 我將如何導入此文件,以便它可用於編寫代碼或使用上述數據回答問題。 我試過:

 open('C:/animallog1.txt', 'r') 

但它不起作用並指出FileNotFoundError: [Errno 2] No such file or directory: 'C:/animallog1.txt'有人可以幫我解決這個問題FileNotFoundError: [Errno 2] No such file or directory: 'C:/animallog1.txt'

open('C:\\animallog1.txt', 'r') 
  1. 文件animallog1.txt 是否存在?

  2. 在 Windows 上,您應該注意后擋板。

     file = open('c:\\\\path\\\\to\\\\file', 'r')

    file = open(r'c:\\path\\to\\file', 'r')
  3. 檢查您的工作區,您可以使用os.chdir()將目錄更改為c:\\嗎?

首先,如果您使用的是 Windows,則必須使用反斜杠。 有幾種方法可以做到這一點:一種是像其他人指出的那樣使用雙反斜杠,另一種是使用osos.path庫中的各種常量和函數:

import os
filename = "C:" + os.sep + "animallog1.txt"

其次,執行此操作的“正確”方法是使用with語句:

with open(filename) as f: #'r' is default
    for line in f:
        a, date, s = line.split(":")
        # ...

with語句的作用是保證文件在離開with塊時關閉。 否則文件不會被關閉,直到 Python 垃圾收集器找到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM