我想知道采用包含这种格式的行的文本文件的最佳方法是什么:姓:名:猫的数目:狗的数目:鱼的数目:其他宠物的数目
并生成一个文本文件,其中包含以下格式的行:姓氏:宠物总数
例如,将使用一个包含以下内容的文本文件:
Apple:Tim:0:0:3:0
Jobs:Steve:0:0:5:2
Da Kid:Billie:0:1:0:1
White:Walter:2:1:1:0
Bond:James:2:2:3:0
Stark:Tony:0:1:2:0
Wayne:Bruce:0:0:0:0
并输出一个看起来像这样的文本文件:
Tim Apple:3
Steve Jobs:7
Bille Da Kid:2
Walter White:4
James Bond:7
Tony Stark:3
Bruce Wayne:0
到目前为止,我一直在尝试但没有成功:
let namesFile = "Names"
let dir = try? FileManager.default.url(for: .documentDirectory,
in: .userDomainMask, appropriateFor: nil, create: true)
// If the directory was found, we write a file to it and read it back
if let fileURL = dir?.appendingPathComponent(namesFile).appendingPathExtension("txt") {
print (fileURL)
var petSum = 0;
do {
let entriesString = try String(contentsOf: fileURL)
let entries = entriesString.components(separatedBy: "\n")
for entry in entries {
let namePets = entry.components(separatedBy: ":")
if (namePets.indices.contains(1)) {
var sum = 0;
print(namePets[1])
print(namePets[0])
for namePet in namePets {
if let intArg = Int(namePet) {
sum = sum + intArg
}
}
print (sum)
print ("\n")
}
}
} catch {
print("Failed reading from URL, Error: " + error.localizedDescription)
}
}
else {
print("didn't work")
}
/*
// Read from the file
var inString = ""
// Write to the file named Test
let outString = "Write this text to the file"
do {
try outString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
*/
非常感谢您的帮助,谢谢!
只需创建一个string
,然后将其写入另一个文件,
do {
let entriesString = try String(contentsOf: fileURL)
let entries = entriesString.components(separatedBy: "\n")
var outputString = ""
for entry in entries {
let namePets = entry.components(separatedBy: ":")
if (namePets.indices.contains(1)) {
var sum = 0
for namePet in namePets {
if let intArg = Int(namePet) {
sum = sum + intArg
}
}
let line = text.isEmpty ? "" : "\n"
outputString = outputString + line + "\(namePets[1]) \(namePets[0]):\(sum)"
}
}
print(outputString)
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let newFileURL = dir.appendingPathComponent("NewNames.txt")
try outputString.write(to: newFileURL, atomically: false, encoding: .utf8)
}
} catch {
print("Failed reading from URL, Error: " + error.localizedDescription)
}