簡體   English   中英

如何使用python正確讀取和修改文件

[英]how to properly read and modify a file using python

我正在嘗試從文件中刪除所有(非空格)空白字符,並用逗號替換所有空格。 這是我目前的代碼:

def file_get_contents(filename):
  with open(filename) as f:
    return f.read()

content = file_get_contents('file.txt')
content = content.split
content = str(content).replace(' ',',')
with open ('file.txt', 'w') as f:
  f.write(content)

當它運行時,它用以下內容替換文件的內容:

<built-in,method,split,of,str,object,at,0x100894200>

您遇到的主要問題是您將方法content.split分配給內容,而不是調用它並分配其返回值。 如果您在該分配后打印出content ,它將是: <built-in method split of str object at 0x100894200>這不是您想要的。 通過添加括號來修復它,使其成為方法的調用,而不僅僅是對它的引用:

content = content.split()

我認為你在解決這個問題之后可能仍有問題。 str.split返回一個列表,然后使用str調整回一個字符串(在嘗試用逗號替換空格之前)。 這將給你方括號和引號,你可能不想要,你會得到一堆額外的逗號。 相反,我建議像這樣使用str.join方法:

content = ",".join(content) # joins all members of the list with commas

我不確定這是不是你想要的。 使用split將替換文件中的所有換行符,因此您最終會得到一行,其中有許多單詞用逗號分隔。

拆分內容時,您忘記調用該功能。 一旦你拆分,它的一個數組,所以你應該循環替換東西。

def file_get_contents(filename):
  with open(filename) as f:
    return f.read()

content = file_get_contents('file.txt')
content = content.split() <- HERE
content = [c.replace(' ',',') for c in content]
content = "".join(content)
with open ('file.txt', 'w') as f:
  f.write(content)

如果你想替換字符我認為你最好使用python的re模塊進行正則表達式。 示例代碼如下:

import re

def file_get_contents(filename):
  with open(filename) as f:
    return f.read()

if __name__=='__main__':
    content = file_get_contents('file.txt')
    # First replace any spaces with commas, then remove any other whitespace
    new_content = re.sub('\s', '', re.sub(' ', ',', content))
    with open ('new_file.txt', 'w') as f:
      f.write(new_content)

它更簡潔,然后嘗試分裂所有的時間,並給你一點點靈活性。 還要注意你打開和閱讀代碼的文件有多大 - 你可能要考慮使用行迭代器或其他東西而不是一次讀取所有文件內容

暫無
暫無

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

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