删除文件的空白空间 python
delete empty spaces of files python
我有一个包含几行的文件,其中一些有空格。
x=20
y=3
z = 1.5
v = 0.1
我想删除那些空格并将每一行放入一个字典中,其中“=”符号之前的元素将是键,“=”符号之后的元素将是它的值。
但是,我的代码不起作用,至少 "delete empty spaces" 部分不起作用。这是代码:
def copyFile(filename):
"""
function's contract
"""
with open(filename, 'r') as inFile:
for line in inFile:
cleanedLine = line.strip()
if cleanedLine:
firstPart, secondPart = line.split('=')
dic[firstPart] = float(secondPart)
inFile.close()
return dic
清除空格后,我的文件应该是这样的
x=20
y=3
z=1.5
v=0.1
但是没有用。我做错了什么?
要删除空格,请尝试使用 .replace(" ", "") 而不是 .strip()
拆分字符串后需要strip
。这是假设唯一不需要的空格位于 =
周围或该行内容之前或之后。
from ast import literal_eval
def copyFile(filename):
with open(filename, 'r') as inFile:
split_lines = (line.split('=', 1) for line in inFile)
d = {key.strip(): literal_eval(value.strip()) for key, value in split_lines}
return d
您的代码存在一些问题。
首先,你永远不会定义 dic
所以当你尝试向它添加键时你会得到一个 NameError
.
其次,您不需要 inFile.close()
,因为您在 with
中打开它,它将始终在块外关闭它。
第三,你的函数名和变量名不符合PEP8标准。
第四,你需要strip
每个部分。
下面是一些有效且看起来不错的代码:
def copy_file(filename):
"""
function's contract
"""
dic = {}
with open(filename, 'r') as in_file:
for line in in_file:
cleaned_line = line.strip()
if cleaned_line:
first_part, second_part = line.split('=')
dic[first_part.strip()] = float(second_part.strip())
return dic
你有两个问题:
您不删除白色 space 的原因是您在整条线路上调用 .strip()
。 strip()
删除字符串 beginning 和 end 处的白色 space,而不是中间。相反,在 firstpart
和 lastpart
上调用 .strip()
。
这将修复您正在创建的内存中字典,但它不会对文件进行任何更改,因为您永远不会写入文件。您需要创建一个 second 文件副本,您将 strip()
ed 值写入其中,然后在最后用新文件替换原始文件。
我有一个包含几行的文件,其中一些有空格。
x=20
y=3
z = 1.5
v = 0.1
我想删除那些空格并将每一行放入一个字典中,其中“=”符号之前的元素将是键,“=”符号之后的元素将是它的值。
但是,我的代码不起作用,至少 "delete empty spaces" 部分不起作用。这是代码:
def copyFile(filename):
"""
function's contract
"""
with open(filename, 'r') as inFile:
for line in inFile:
cleanedLine = line.strip()
if cleanedLine:
firstPart, secondPart = line.split('=')
dic[firstPart] = float(secondPart)
inFile.close()
return dic
清除空格后,我的文件应该是这样的
x=20
y=3
z=1.5
v=0.1
但是没有用。我做错了什么?
要删除空格,请尝试使用 .replace(" ", "") 而不是 .strip()
拆分字符串后需要strip
。这是假设唯一不需要的空格位于 =
周围或该行内容之前或之后。
from ast import literal_eval
def copyFile(filename):
with open(filename, 'r') as inFile:
split_lines = (line.split('=', 1) for line in inFile)
d = {key.strip(): literal_eval(value.strip()) for key, value in split_lines}
return d
您的代码存在一些问题。
首先,你永远不会定义 dic
所以当你尝试向它添加键时你会得到一个 NameError
.
其次,您不需要 inFile.close()
,因为您在 with
中打开它,它将始终在块外关闭它。
第三,你的函数名和变量名不符合PEP8标准。
第四,你需要strip
每个部分。
下面是一些有效且看起来不错的代码:
def copy_file(filename):
"""
function's contract
"""
dic = {}
with open(filename, 'r') as in_file:
for line in in_file:
cleaned_line = line.strip()
if cleaned_line:
first_part, second_part = line.split('=')
dic[first_part.strip()] = float(second_part.strip())
return dic
你有两个问题:
您不删除白色 space 的原因是您在整条线路上调用
.strip()
。strip()
删除字符串 beginning 和 end 处的白色 space,而不是中间。相反,在firstpart
和lastpart
上调用.strip()
。这将修复您正在创建的内存中字典,但它不会对文件进行任何更改,因为您永远不会写入文件。您需要创建一个 second 文件副本,您将
strip()
ed 值写入其中,然后在最后用新文件替换原始文件。