zoukankan      html  css  js  c++  java
  • 文件处理

     1 # *-* coding: utf-8 *-*
     2 
     3 import os
     4 
     5 #os.getcwd() 当前工作目录
     6 os.getcwd()
     7 
     8 #data = open('test1.txt')
     9 #print(data.readline())
    10 
    11 #返回文件起始位置
    12 #data.seek(0)
    13 
    14 #if os.path.exists('test.txt'):
    15 try:
    16     data = open('test.txt')         #打开文件
    17     for line in data:
    18         try:
    19             if not line.find(":") == -1:
    20                 #print(line.strip('\n'))
    21                 #文件处理, 过滤换行后, split 字符串分割操作
    22                 (role, line_spoken) = line.strip('\n').split(":", 1)
    23                 print(role + ' said: ' + line_spoken)
    24         except ValueError:
    25             pass
    26 
    27     data.close()
    28 #else:
    29 except IOError:
    30     print("The data file is missing!")
     1 # *-* coding: utf-8 *-*
     2 
     3 import os
     4 
     5 man = []
     6 other = []
     7 
     8 try:
     9     data = open('test1.txt')                #打开文件
    10     for line in data:
    11         try:
    12             #字符串处理, 读取一行过滤掉换行符, split 分割
    13             (role, line_spoken) = line.strip('\n').split(':', 1)
    14             line_spoken = line_spoken.strip()       #过滤掉前后空白
    15             if role == 'Man':
    16                 man.append(line_spoken)
    17             elif role == 'Other Man':
    18                 other.append(line_spoken)
    19 
    20         except:
    21             pass
    22     data.close()
    23 
    24 except IOError:
    25     print("The datafile is missing!")
    26 
    27 try:
    28     print os.getcwd()
    29     man_file = open('man_data.txt', 'w')
    30     other_file = open('other_data.txt', 'w')    #打开文件, 如果文件不存在, 自动创建
    31 
    32     man_file.write(str(man))                    #将列表转换为字符串,写入文件. 不转换产生异常
    33     other_file.write(str(other))
    34 
    35 except IOError:
    36     print("FileError!")
    37 finally:
    38     man_file.close()
    39     other_file.close()
  • 相关阅读:
    mysql操作
    Linux内核事件通知链学习
    C++双端队列学习
    tune的结果图是什么
    conda环境备份
    Could not load dynamic library 'libcudart.so.11.0';
    Unexpected error while saving file: xxx.ipynb database or disk is full
    友元函数与友元类
    构造函数初始化必须采用初始化列表的情况
    模型集成04-GMM
  • 原文地址:https://www.cnblogs.com/Roger1227/p/3130323.html
Copyright © 2011-2022 走看看