前言
python读取txt文件,删除文中所有空格,并写入新的文件。具体操作文件以股吧评论数据为例子
一、with open() as x:方式读写文件?
在with的结构下处理文件,在结构内控制文件的读写,可防止文件泄露
二、使用步骤
1.读取并打印文件内容
代码如下:
with open('./data/positive.txt',encoding='utf8') as file_object: # 以utf8解码格式打开整个文件
contents = file_object.read() # 读取整个文件到contents中
print(contents)
2.读取文件,去除空格,写入新文件
代码如下:
pos_filename = './data/positive.txt' # 要处理的文件路径
neg_filename = './data/negative.txt'
with open(pos_filename,encoding='utf8') as positive_lines: # 以utf8格式处理文件并打开
pos_lines = positive_lines.read() # 以list pos_lines读取整个文件
pos_lines = pos_lines.replace(' ','') # 把文件list中的所有空格替换掉,也可以描述成删除文件中所有空格
with open(neg_filename,encoding='utf8') as negative_lines:
neg_lines = negative_lines.read()
neg_lines = neg_lines.replace(' ','')
print(pos_lines) # 打印处理后的list
print(neg_lines)
new_pos_filename = './data/new_pos.txt' # 没有这个文件,后面的处理会新建这个txt文件
new_neg_filename = './data/new_neg.txt'
with open(new_pos_filename,'w',encoding='utf8') as positive_new_lines: # 以写入模式打开文件
positive_new_lines.write(pos_lines) # 把list写入新文件中
with open(new_neg_filename,'w',encoding='utf8') as negative_new_lines:
negative_new_lines.write(neg_lines)
总结
吾尝终日而思矣,不如须臾之所学也。