python數字分割 - python讀檔字串
在Python中,如何逐行讀取文件到列表中? (20)
用Python 2 + 3讀寫文本文件; 適用於unicode
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Define data
lines = [' A first string ',
'A unicode sample: €',
'German: äöüß']
# Write text file
with open('file.txt', 'w') as fp:
fp.write('\n'.join(lines))
# Read text file
with open('file.txt', 'r') as fp:
read_lines = fp.readlines()
read_lines = [line.rstrip('\n') for line in read_lines]
print(lines == read_lines)
注意事項:
-
with
一個所謂的上下文管理器 。 它確保打開的文件再次關閉。 - 所有這些簡單地製作
.strip()
或.rstrip()
解決方案都無法重現這些lines
因為它們也會剝去空白區域。
通用文件結尾
.txt
更高級的文件寫入/讀取
- CSV:超簡單格式( 讀寫 )
- JSON:寫出人類可讀的數據很棒; 非常常用( 讀寫 )
- YAML:YAML是JSON的超集,但更易於閱讀( 讀取和寫入 , 比較JSON和YAML )
- pickle:一種Python序列化格式( 讀寫 )
- MessagePack ( Python包 ):更緊湊的表示( 讀寫 )
- HDF5 ( Python包 ):很好的矩陣( 讀寫 )
- XML:存在*嘆*( write )
對於您的應用程序,以下內容可能很重要:
- 其他編程語言的支持
- 閱讀/寫作表現
- 緊湊(文件大小)
另請參閱: 比較數據序列化格式
如果您正在尋找製作配置文件的方式,您可能需要閱讀我的簡短文章Python配置文件
如何在Python中讀取文件的每一行並將每行存儲為列表中的元素?
我想逐行讀取文件,並將每行添加到列表的末尾。
命令行版本
#!/bin/python3
import os
import sys
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
filename = dname + sys.argv[1]
arr = open(filename).read().split("\n")
print(arr)
運行:
python3 somefile.py input_file_name.txt
最簡單的方法來做到這一點
一個簡單的方法是:
- 將整個文件作為字符串讀取
- 逐行分割字符串
在一行中,這將給出:
lines = open('C:/path/file.txt').read().splitlines()
一個真正簡單的方法:
with open(file) as g:
stuff = g.readlines()
如果你想讓它成為一個完整的程序,請在下面輸入:
file = raw_input ("Enter EXACT file name: ")
with open(file) as g:
stuff = g.readlines()
print (stuff)
exit = raw_input("Press enter when you are done.")
由於某些原因,它不能正確讀取.py文件。
你可以打開你的文件閱讀使用
file1 = open("filename","r")
# and for reading use
lines = file1.readlines()
file1.close()
列表行將包含所有行作為單獨的元素,並且可以使用lines["linenumber-1"]
調用特定元素,因為python從0開始計數。
另一個選項是numpy.genfromtxt
,例如:
import numpy as np
data = np.genfromtxt("yourfile.dat",delimiter="\n")
這將使data
成為NumPy數組,其行數與文件中的數量相同。
如果你不關心關閉文件,這個單行工作:
lines = open('file.txt').read().split("\n")
傳統的方式:
fp = open('file.txt') # open file on read mode
lines = fp.read().split("\n") # create a list containing all lines
fp.close() # close file
使用(推薦):
with open('file.txt') as fp:
lines = fp.read().split("\n")
如果你想\n
納入:
with open(fname) as f:
content = f.readlines()
如果你不想\n
包括:
with open(fname) as f:
content = f.read().splitlines()
如果您想從命令行或標準輸入讀取文件,您也可以使用fileinput
模塊:
# reader.py
import fileinput
content = []
for line in fileinput.input():
content.append(line.strip())
fileinput.close()
將文件傳遞給它就像這樣:
$ python reader.py textfile.txt
在這裡閱讀更多: http://docs.python.org/2/library/fileinput.html : http://docs.python.org/2/library/fileinput.html
您可以通過以下代碼輕鬆完成此操作:
lines = open(filePath).readlines()
我會這樣做。
lines = []
with open("myfile.txt") as f:
for line in f:
lines.append(line)
據我所知,Python沒有一個本地數組數據結構。 但它確實支持列表數據結構,它比數組更容易使用。
array = [] #declaring a list with name '**array**'
with open(PATH,'r') as reader :
for line in reader :
array.append(line)
正如所建議的那樣,您可以簡單地執行以下操作:
with open('/your/path/file') as f:
my_lines = f.readlines()
請注意,這種方法有兩個缺點:
1)將所有行存儲在內存中。 在一般情況下,這是一個非常糟糕的主意。 該文件可能非常大,並且可能會導致內存不足。 即使它不大,也只是浪費記憶。
2)這不允許在讀取它們時處理每一行。 所以如果你在這之後處理你的線條,效率不高(需要兩遍而不是一次)。
一般情況下更好的方法如下:
with open('/your/path/file') as f:
for line in f:
process(line)
您可以以任何方式定義您的過程功能。 例如:
def process(line):
if 'save the world' in line.lower():
superman.save_the_world()
( Superman
課程的實施僅作為你的練習)。
這將很好地適用於任何文件大小,並且只需1遍即可完成文件。 這通常是泛型解析器的工作原理。
用這個:
import pandas as pd
data = pd.read_csv(filename) # You can also add parameters such as header, sep, etc.
array = data.values
data
是一種數據幀類型,並使用值來獲得ndarray。 你也可以使用array.tolist()
來獲得一個列表。
請參閱輸入和輸出 :
with open('filename') as f:
lines = f.readlines()
或剝離換行符:
lines = [line.rstrip('\n') for line in open('filename')]
編者按:Janus Troelsen的評論暗示,這個回答的原始whitespace-stripping命令line.strip()
將刪除所有前導和尾隨空白,而不僅僅是尾隨\n
。
這將從文件中產生一行“數組”。
lines = tuple(open(filename, 'r'))
這比必要更明確,但是做你想要的。
with open("file.txt", "r") as ins:
array = []
for line in ins:
array.append(line)
通過對文件使用列表推導還有另外一個選項;
lines = [line.rstrip() for line in open('file.txt')]
這應該是更有效的方式,因為大部分工作都是在Python解釋器中完成的。
lines = list(open("dict.lst", "r"))
linesSanitized = map(lambda each:each.strip("\n"), lines)
print linesSanitized
with open(fname) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
我猜你的意思是list
而不是數組。