我這樣做是一種更容易理解的方式,並且使用更少的捷徑來讓您進一步瞭解它的工作方式和原因。以前的答案很有用,但如果您對某些內置函數不熟悉,您將無法理解該函數在做什麼。
因爲你沒有發佈代碼,所以我決定這樣做,因爲除了基本的Python語法之外,你可能不熟悉這些東西,因爲你說的這個問題看起來好像你沒有嘗試也沒有任何線索。如何處理這個問題
以下是基本的Python做到這一點的步驟:
首先,你應該閱讀您的文件到列表保管:
my_file = 'really_big_file.txt'
hold_lines = []
with open(my_file,'r') as text_file:
for row in text_file:
hold_lines.append(row)
其次,你需要設置一種創造新的方式文件名稱!我建議一環一對夫婦櫃檯沿:
outer_count = 1
line_count = 0
sorting = True
while sorting:
count = 0
increment = (outer_count-1) * 300
left = len(hold_lines) - increment
file_name = "small_file_" + str(outer_count * 300) + ".txt"
第三,循環裏面,你需要一些嵌套的循環,將正確的行保存到一個數組:
hold_new_lines = []
if left < 300:
while count < left:
hold_new_lines.append(hold_lines[line_count])
count += 1
line_count += 1
sorting = False
else:
while count < 300:
hold_new_lines.append(hold_lines[line_count])
count += 1
line_count += 1
最後一件事,又在你的第一個循環,你需要編寫新的文件,並添加您的最後一個計數器增量所以你的循環將再次經歷譜寫新的文件
outer_count += 1
with open(file_name,'w') as next_file:
for row in hold_new_lines:
next_file.write(row)
注:如果行數不整除b y 300,最後一個文件將有一個不對應於最後一個文件行的名稱。
理解這些循環爲什麼起作用很重要。您已將它設置爲在下一個循環中寫入的文件的名稱發生更改,因爲您的名稱取決於變化的變量。這是文件訪問,開放,寫作,組織等一個非常有用的腳本工具
如果你不能遵循什麼是什麼環路,這裏是功能的全部:
my_file = 'really_big_file.txt'
sorting = True
hold_lines = []
with open(my_file,'r') as text_file:
for row in text_file:
hold_lines.append(row)
outer_count = 1
line_count = 0
while sorting:
count = 0
increment = (outer_count-1) * 300
left = len(hold_lines) - increment
file_name = "small_file_" + str(outer_count * 300) + ".txt"
hold_new_lines = []
if left < 300:
while count < left:
hold_new_lines.append(hold_lines[line_count])
count += 1
line_count += 1
sorting = False
else:
while count < 300:
hold_new_lines.append(hold_lines[line_count])
count += 1
line_count += 1
outer_count += 1
with open(file_name,'w') as next_file:
for row in hold_new_lines:
next_file.write(row)
如果您使用的是python 3.x中的第一個腳本,請將''''izip_longest''替換爲新的''zip_longest''' https://docs.python.org/3/library/ itertools.html#itertools.zip_longest – 2017-03-22 08:45:27