使用 Swift 读取文本文件的 Pythonic 方式

标签 python file cocoa parsing swift

我了解 Python,并且正在尝试学习 Swift...我正在尝试弄清楚如何从绝对文件路径读取纯文本文件

在 Python 中,

#!/usr/bin/python

path= '/users/mu/desktop/test_file.txt'    
in_file= open(path,'w').read() #Open the file for reading

for line in in_file.split('\n'): #Split it by line breaks and print the lines
    print line

尝试过这个:Swift - Read Files 得到:“String.Type 没有成员名称 stringWithContentsOfFile”

在 Python 中,这非常简单。必须有一种非常简单的方法来读取文本文件并创建由换行符分隔的字符串列表。

我的问题是如何读取文本文件,以便可以迭代各行

一旦我阅读了该文件,我就可以:

for line in in_file
    {
    println(line)
    }

最佳答案

您可以使用 NSFileManager 和 NSString 来解析这些行 例如:

    var path = "somePath"
    let fileManager = NSFileManager.defaultManager()
    let data:NSData = fileManager.contentsAtPath(path)!
    var strs = NSString(data: data, encoding: NSUTF8StringEncoding)

关于使用 Swift 读取文本文件的 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29090460/

相关文章:

c - C 中不同文件循环中的 Search_string

python - 如何让 Actor 同时做两件事?

Python SymPy : Error while solving inequality

java - 使用 Java 创建一个大小为 1024 字节的测试文件

java - 编译器是否可以有最大输出?

xcode - 在 macOS 应用程序中绘制彩色矩形 (Swift)

swift - 使用NSVisualEffectView时如何添加按钮

python - sendLine 中的扭曲类型错误

python - 属性错误: 'str' object has no attribute 'descendants'

ios - NSNetService dictionaryFromTXTRecord 对无效输入的断言失败